• Connecting Devices Wirelessly 无线设备连接


    Using Network Service Discovery

    Creating P2P Connections with Wi-Fi

    Using Wi-Fi P2P for Service Discovery

    Using Network Service Discovery

    来源:http://developer.android.com/training/connect-devices-wirelessly/nsd.html

    Register Your Service on the Network

    public void initializeRegistrationListener() {
        mRegistrationListener = new NsdManager.RegistrationListener() {
    
            @Override
            public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
                // Save the service name.  Android may have changed it in order to
                // resolve a conflict, so update the name you initially requested
                // with the name Android actually used.
                mServiceName = NsdServiceInfo.getServiceName();
            }
    
            @Override
            public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Registration failed!  Put debugging code here to determine why.
            }
    
            @Override
            public void onServiceUnregistered(NsdServiceInfo arg0) {
                // Service has been unregistered.  This only happens when you call
                // NsdManager.unregisterService() and pass in this listener.
            }
    
            @Override
            public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Unregistration failed.  Put debugging code here to determine why.
            }
        };
    }
    public void registerService(int port) {
        NsdServiceInfo serviceInfo  = new NsdServiceInfo();
        serviceInfo.setServiceName("NsdChat");
        serviceInfo.setServiceType("_http._tcp.");
        serviceInfo.setPort(port);
    
        mNsdManager = Context.getSystemService(Context.NSD_SERVICE);
    
        mNsdManager.registerService(
                serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
    }

    Discover Services on the Network

    public void initializeDiscoveryListener() {
    
        // Instantiate a new DiscoveryListener
        mDiscoveryListener = new NsdManager.DiscoveryListener() {
    
            //  Called as soon as service discovery begins.
            @Override
            public void onDiscoveryStarted(String regType) {
                Log.d(TAG, "Service discovery started");
            }
    
            @Override
            public void onServiceFound(NsdServiceInfo service) {
                // A service was found!  Do something with it.
                Log.d(TAG, "Service discovery success" + service);
                if (!service.getServiceType().equals(SERVICE_TYPE)) {
                    // Service type is the string containing the protocol and
                    // transport layer for this service.
                    Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
                } else if (service.getServiceName().equals(mServiceName)) {
                    // The name of the service tells the user what they'd be
                    // connecting to. It could be "Bob's Chat App".
                    Log.d(TAG, "Same machine: " + mServiceName);
                } else if (service.getServiceName().contains("NsdChat")){
                    mNsdManager.resolveService(service, mResolveListener);
                }
            }
    
            @Override
            public void onServiceLost(NsdServiceInfo service) {
                // When the network service is no longer available.
                // Internal bookkeeping code goes here.
                Log.e(TAG, "service lost" + service);
            }
    
            @Override
            public void onDiscoveryStopped(String serviceType) {
                Log.i(TAG, "Discovery stopped: " + serviceType);
            }
    
            @Override
            public void onStartDiscoveryFailed(String serviceType, int errorCode) {
                Log.e(TAG, "Discovery failed: Error code:" + errorCode);
                mNsdManager.stopServiceDiscovery(this);
            }
    
            @Override
            public void onStopDiscoveryFailed(String serviceType, int errorCode) {
                Log.e(TAG, "Discovery failed: Error code:" + errorCode);
                mNsdManager.stopServiceDiscovery(this);
            }
        };
    }
     mNsdManager.discoverServices(
            SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);

    Connect to Services on the Network

    public void initializeResolveListener() {
        mResolveListener = new NsdManager.ResolveListener() {
    
            @Override
            public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Called when the resolve fails.  Use the error code to debug.
                Log.e(TAG, "Resolve failed" + errorCode);
            }
    
            @Override
            public void onServiceResolved(NsdServiceInfo serviceInfo) {
                Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
    
                if (serviceInfo.getServiceName().equals(mServiceName)) {
                    Log.d(TAG, "Same IP.");
                    return;
                }
                mService = serviceInfo;
                int port = mService.getPort();
                InetAddress host = mService.getHost();
            }
        };
    }

    Unregister Your Service on Application Close

    //In your application's Activity
    
        @Override
        protected void onPause() {
            if (mNsdHelper != null) {
                mNsdHelper.tearDown();
            }
            super.onPause();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            if (mNsdHelper != null) {
                mNsdHelper.registerService(mConnection.getLocalPort());
                mNsdHelper.discoverServices();
            }
        }
    
        @Override
        protected void onDestroy() {
            mNsdHelper.tearDown();
            mConnection.tearDown();
            super.onDestroy();
        }
    
        // NsdHelper's tearDown method
            public void tearDown() {
            mNsdManager.unregisterService(mRegistrationListener);
            mNsdManager.stopServiceDiscovery(mDiscoveryListener);
        }
    

    Creating P2P Connections with Wi-Fi

    Set Up a Broadcast Receiver and Peer-to-Peer Manager

    private final IntentFilter intentFilter = new IntentFilter();
    ...
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        //  Indicates a change in the Wi-Fi P2P status.
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    
        // Indicates a change in the list of available peers.
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    
        // Indicates the state of Wi-Fi P2P connectivity has changed.
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    
        // Indicates this device's details have changed.
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    
        ...
    }
    @Override
    
    Channel mChannel;
    
    public void onCreate(Bundle savedInstanceState) {
        ....
        mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel = mManager.initialize(this, getMainLooper(), null);
    }

    BroadcastReceiver class

     @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
                // Determine if Wifi P2P mode is enabled or not, alert
                // the Activity.
                int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
                if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                    activity.setIsWifiP2pEnabled(true);
                } else {
                    activity.setIsWifiP2pEnabled(false);
                }
            } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
    
                // The peer list has changed!  We should probably do something about
                // that.
    
            } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
    
                // Connection state changed!  We should probably do something about
                // that.
    
            } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
                DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
                        .findFragmentById(R.id.frag_list);
                fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
                        WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
    
            }
        }

    Initiate Peer Discovery

    mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
    
            @Override
            public void onSuccess() {
                // Code for when the discovery initiation is successful goes here.
                // No services have actually been discovered yet, so this method
                // can often be left blank.  Code for peer discovery goes in the
                // onReceive method, detailed below.
            }
    
            @Override
            public void onFailure(int reasonCode) {
                // Code for when the discovery initiation fails goes here.
                // Alert the user that something went wrong.
            }
    });

    Fetch the List of Peers

        private List peers = new ArrayList();
        ...
    
        private PeerListListener peerListListener = new PeerListListener() {
            @Override
            public void onPeersAvailable(WifiP2pDeviceList peerList) {
    
                // Out with the old, in with the new.
                peers.clear();
                peers.addAll(peerList.getDeviceList());
    
                // If an AdapterView is backed by this data, notify it
                // of the change.  For instance, if you have a ListView of available
                // peers, trigger an update.
                ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
                if (peers.size() == 0) {
                    Log.d(WiFiDirectActivity.TAG, "No devices found");
                    return;
                }
            }
        }
    public void onReceive(Context context, Intent intent) {
        ...
        else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
    
            // Request available peers from the wifi p2p manager. This is an
            // asynchronous call and the calling activity is notified with a
            // callback on PeerListListener.onPeersAvailable()
            if (mManager != null) {
                mManager.requestPeers(mChannel, peerListListener);
            }
            Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
        }...
    }

    Connect to a Peer

     @Override
        public void connect() {
            // Picking the first device found on the network.
            WifiP2pDevice device = peers.get(0);
    
            WifiP2pConfig config = new WifiP2pConfig();
            config.deviceAddress = device.deviceAddress;
            config.wps.setup = WpsInfo.PBC;
    
            mManager.connect(mChannel, config, new ActionListener() {
    
                @Override
                public void onSuccess() {
                    // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
                }
    
                @Override
                public void onFailure(int reason) {
                    Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }

      WifiP2pManager.ConnectionInfoListener

     @Override
        public void onConnectionInfoAvailable(final WifiP2pInfo info) {
    
            // InetAddress from WifiP2pInfo struct.
            InetAddress groupOwnerAddress = info.groupOwnerAddress.getHostAddress());
    
            // After the group negotiation, we can determine the group owner.
            if (info.groupFormed && info.isGroupOwner) {
                // Do whatever tasks are specific to the group owner.
                // One common case is creating a server thread and accepting
                // incoming connections.
            } else if (info.groupFormed) {
                // The other device acts as the client. In this case,
                // you'll want to create a client thread that connects to the group
                // owner.
            }
        }
     ...
            } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
    
                if (mManager == null) {
                    return;
                }
    
                NetworkInfo networkInfo = (NetworkInfo) intent
                        .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
    
                if (networkInfo.isConnected()) {
    
                    // We are connected with the other device, request connection
                    // info to find group owner IP
    
                    mManager.requestConnectionInfo(mChannel, connectionListener);
                }
                ...

    Using Wi-Fi P2P for Service Discovery

    Add a Local Service

     private void startRegistration() {
            //  Create a string map containing information about your service.
            Map record = new HashMap();
            record.put("listenport", String.valueOf(SERVER_PORT));
            record.put("buddyname", "John Doe" + (int) (Math.random() * 1000));
            record.put("available", "visible");
    
            // Service information.  Pass it an instance name, service type
            // _protocol._transportlayer , and the map containing
            // information other devices will want once they connect to this one.
            WifiP2pDnsSdServiceInfo serviceInfo =
                    WifiP2pDnsSdServiceInfo.newInstance("_test", "_presence._tcp", record);
    
            // Add the local service, sending the service info, network channel,
            // and listener that will be used to indicate success or failure of
            // the request.
            mManager.addLocalService(channel, serviceInfo, new ActionListener() {
                @Override
                public void onSuccess() {
                    // Command successful! Code isn't necessarily needed here,
                    // Unless you want to update the UI or add logging statements.
                }
    
                @Override
                public void onFailure(int arg0) {
                    // Command failed.  Check for P2P_UNSUPPORTED, ERROR, or BUSY
                }
            });
        }

    Discover Nearby Services

    final HashMap<String, String> buddies = new HashMap<String, String>();
    ...
    private void discoverService() {
        DnsSdTxtRecordListener txtListener = new DnsSdTxtRecordListener() {
            @Override
            /* Callback includes:
             * fullDomain: full domain name: e.g "printer._ipp._tcp.local."
             * record: TXT record dta as a map of key/value pairs.
             * device: The device running the advertised service.
             */
    
            public void onDnsSdTxtRecordAvailable(
                    String fullDomain, Map record, WifiP2pDevice device) {
                    Log.d(TAG, "DnsSdTxtRecord available -" + record.toString());
                    buddies.put(device.deviceAddress, record.get("buddyname"));
                }
            };
        ...
    }

    To get the service information, create a WifiP2pManager.DnsSdServiceResponseListener.

    private void discoverService() {
    ...
    
        DnsSdServiceResponseListener servListener = new DnsSdServiceResponseListener() {
            @Override
            public void onDnsSdServiceAvailable(String instanceName, String registrationType,
                    WifiP2pDevice resourceType) {
    
                    // Update the device name with the human-friendly version from
                    // the DnsTxtRecord, assuming one arrived.
                    resourceType.deviceName = buddies
                            .containsKey(resourceType.deviceAddress) ? buddies
                            .get(resourceType.deviceAddress) : resourceType.deviceName;
    
                    // Add to the custom adapter defined specifically for showing
                    // wifi devices.
                    WiFiDirectServicesList fragment = (WiFiDirectServicesList) getFragmentManager()
                            .findFragmentById(R.id.frag_peerlist);
                    WiFiDevicesAdapter adapter = ((WiFiDevicesAdapter) fragment
                            .getListAdapter());
    
                    adapter.add(resourceType);
                    adapter.notifyDataSetChanged();
                    Log.d(TAG, "onBonjourServiceAvailable " + instanceName);
            }
        };
    
        mManager.setDnsSdResponseListeners(channel, servListener, txtListener);
        ...
    }
  • 相关阅读:
    Python(1)-第一天
    读书笔记-单元测试艺术(三)-使用桩对象解除依赖
    Sql2008调试问题
    读书笔记-单元测试艺术(二)-单元测试框架
    读书笔记-单元测试艺术(一)-单元测试的基本知识
    最长回文子串
    最大连续子序列之和,最大连续子序列乘积
    计数排序与位图排序
    筛选法求素数
    传说中的华为面试题(8分钟写出代码)
  • 原文地址:https://www.cnblogs.com/wjw334/p/4305791.html
Copyright © 2020-2023  润新知