Android Official Development Document Training Series Course Chinese: Internet service search for connected wireless devices

Source: Internet
Author: User

Original address: http://android.xsoftlab.net/training/connect-devices-wirelessly/index.html

Introduction

In addition to being able to connect to the server, Android wireless APIs allow two devices under the same network segment to connect, or two devices with a similar physical distance to make connections. Network Service Discovery (NSD) allows applications to scan to find nearby devices that can be connected. Of course the scanned device also needs to open the service. This feature allows the application to have more powerful functions, such as playing games in a room with a companion, or downloading photos from a webcam that has a NSD service, or remotely manipulating other devices in the House (the basis of smart appliances).

This lesson will learn how to search for other devices and connect with them. It is important to note that these key APIs describe how to use the NSD API to search for available services and how to use the Wi-Fi peer-to-peer API to build a wireless connection to peers. This lesson will also learn how to use NSD to search for service providers in a way that is combined with WiFi peer.

Using the web Search service

Use the Network Service Discovery (NSD) service to enable an application to search for devices that are in other support services requirements under the same local network. This can be extremely useful for a variety of peer-to-peer applications, such as using this technology to share files or play multiplayer games. Android's NSD API allows applications to quickly implement this functionality.

This class will learn how to build an application that requires the ability to broadcast the program's name and connection information to the local network and scan the above information. Finally, this session will learn how to make connections to other devices.

Registering a service with the network

Note: This class is optional and you can skip to the next paragraph if you don't need to broadcast your app's service to your local network.

To register a service on a local network, you first need to create a Nsdserviceinfo object that provides information that enables other devices to decide whether to connect.

publicvoidregisterService(int port) {    // Create the NsdServiceInfo object, and populate it.    NsdServiceInfo serviceInfo  new NsdServiceInfo();    // The name is subject to change based on conflicts    // with other services advertised on the same network.    serviceInfo.setServiceName("NsdChat");    serviceInfo.setServiceType("_http._tcp.");    serviceInfo.setPort(port);    ....}

The code above sets the name of the service to "Nsdchat". This name is visible to all devices that use the USD service. One thing to keep in mind is that the name must be unique in this network environment, and Android will automatically handle this name conflict problem. If there are two devices with the name "Nsdchat" in the same environment, then Android will automatically name one of them "nsdchat (1)".

The second parameter sets the type of the service, specifying the transport protocol and Transport layer used. This definition syntax is ".". In the preceding code, the service uses the HTTP protocol that is running on TCP. If a program is providing a print service, its service type should be "_ipp._tcp".

Note: These search service protocols such as NSD, Bonjour are managed uniformly by the International Assigned Numbers Authority (IANA) Internet address encoding distribution authority. You can download the list of service types via the IANA list of service names and port numbers. If the calculation uses a new service type, it should be filed on the IANA Ports and service registration form.

When you set up a port for a service, avoid writing the port to death, because this port may conflict with other ports. Assuming that the application has been using port 1337, it will cause port conflicts with other applications that also use the same port, which can be avoided by using the next available port on the device. Because this information is provided by other applications via broadcast, it is not necessary to know which interface is used by other applications at compile time. Instead, the application obtains the port information by broadcasting before connecting to the device.

If you are using a socket for communication, the following code shows how to initialize a socket and set its port to universal Port 0.

publicvoidinitializeServerSocket() {    // Initialize a server socket on the next available port.    new ServerSocket(0);    // Store the chosen port.    mLocalPort =  mServerSocket.getLocalPort();    ...}

Now that you have defined the Nsdserviceinfo object, the next step is to implement the Registrationlistener interface. This interface is used to notify the application service that the registration of a solution is successful or failed.

 Public void Initializeregistrationlistener() {Mregistrationlistener =NewNsdmanager.registrationlistener () {@Override         Public void onserviceregistered(Nsdserviceinfo nsdserviceinfo) {//Save the service name. Android May has changed it in order to            //Resolve a conflict, so update the name initially requested            //With the name Android actually used.Mservicename = Nsdserviceinfo.getservicename (); }@Override         Public void onregistrationfailed(Nsdserviceinfo serviceinfo,intErrorCode) {//Registration failed! Put Debugging code here to determine why.}@Override         Public void onserviceunregistered(Nsdserviceinfo arg0) {//Service has been unregistered. This is happens when            //Nsdmanager.unregisterservice () and pass in this listener.}@Override         Public void onunregistrationfailed(Nsdserviceinfo serviceinfo,intErrorCode) {//unregistration failed. Put Debugging code here to determine why.}    };}

Now that you have completed all the preparatory work, call the Registerservice () method to complete the service registration.

Note that this method is an async method, so any code that runs after the service completes registration must be executed in the onserviceregistered () method.

publicvoidregisterService(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);}
Search for services on the network

The world of network is full of life, from the Wild network printer to the gentle Network camera, to the intense movement of the body Sense game machine, all is a kind of life. Can enable applications to see the core of these various life forms is the service search function. Applications only need to listen to service broadcasts on the network to determine which services are available and which are not.

The service search feature is similar to the registration of a service, and there are two steps: Set the appropriate search listener and call the Discoverservices () method.

First, instantiate an anonymous class that implements the Nsdmanager.discoverylistener interface:

 Public void Initializediscoverylistener() {//Instantiate a new DiscoverylistenerMdiscoverylistener =NewNsdmanager.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 is                //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,intErrorCode) {LOG.E (TAG,"Discovery failed:error code:"+ ErrorCode); Mnsdmanager.stopservicediscovery ( This); }@Override         Public void onstopdiscoveryfailed(String servicetype,intErrorCode) {LOG.E (TAG,"Discovery failed:error code:"+ ErrorCode); Mnsdmanager.stopservicediscovery ( This); }    };}

The NSD API callbacks These methods in these cases: when the search service starts, when the search service fails, when the service is not found, the service is lost. Note There are several checks when the service is found:

    • 1. The service name found is compared to the name of the service itself to determine if it is a broadcast of its own.
    • 2. Service type Check to verify that the found service can connect.
    • 3. Check the service name to verify that it is connected to the correct program.

The check of the service name is not required, only this step is connected to the specified program. For example, an application simply wants to connect to the same application on another device. In any case, if the program wants to connect to a network printer, it is sufficient to determine whether its service type is "_ipp._tcp".

After you set up the listener, call Discoverservices (), and then pass in the type of service that the program listens to, the search protocol to use, and the listener you just created.

    mNsdManager.discoverServices(        SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
Connect to a network service

When an application finds a service on the network and tries to establish a connection to it, it must first check the connection information for the service through the Resolveservice () method. Implement the Nsdmanager.resolvelistener interface, then pass it into the method Resolveservice (), and then get a Nsdserviceinfo object through the callback method of this interface, which contains the required connection information:

 Public void Initializeresolvelistener() {Mresolvelistener =NewNsdmanager.resolvelistener () {@Override         Public void onresolvefailed(Nsdserviceinfo serviceinfo,intErrorCode) {//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;intPort = Mservice.getport ();        InetAddress host = Mservice.gethost (); }    };}

Once the parsing is complete, the program obtains detailed service information including IP address and port number. This provides help for networks that are connected to the service.

Logout Service

It is important to shut down the NSD function properly during the lifetime of the program. Unregistering a service when the program shuts down helps prevent other programs from thinking that the program is still alive and tries to establish a connection with it. In addition, the service search feature is expensive, so the service should be closed when activity is stopped and opened again when activity restarts. The application should rewrite the corresponding activity's lifecycle callback method and insert the appropriate code in these methods to start or close the service broadcast and service search functionality.

//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); }

Android Official Development Document Training Series Course Chinese: Internet service search for connected wireless devices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.