Android Official Development Document Training Series Course Chinese version: Connect wireless devices via peer Search Network Service

Source: Internet
Author: User

Original address: http://android.xsoftlab.net/training/connect-devices-wirelessly/nsd-wifi-direct.html

The first lesson of this stage, Using Network Service Discovery, shows how to search for local network services. However, using the Wi-Fi peer search service can directly search nearby devices without having to go through the local network specifically. This feature allows communication between different devices without a local network or hotspot.

Although the API here is similar to the NSD API, the implementation process is completely different. This lesson shows you how to search for available services in a nearby Wi-Fi peer network. This lesson is based on the familiarity with the Wi-Fi peer API.

Set up a manifest file

If you want to use Wi-Fi peer technology, you need to add change_wifi_state, Access_wifi_state, Internet three permissions to your program's manifest file. Although Wi-Fi peer does not require an Internet connection, it requires the use of standard Java socket Communication technology, so internet access is required:

<manifest xmlns:android="Http://schemas.android.com/apk/res/android"     package ="Com.example.android.nsdchat" ... <uses-permissionandroid:required= "true"android:name=" Android.permission.ACCESS_WIFI_STATE "/>                            <uses-permissionandroid:required= "true"android:name=" Android.permission.CHANGE_WIFI_STATE "/>                    <uses-permissionandroid:required= "true"android:name=" Android.permission.INTERNET "/>                ...
Add Local Service

If the program provides local services, you will also need to register the service with the search service. Once the local service completes the registration, the framework automatically responds to the Search service request at the other end point.

The following procedures are available for creating a local network:

    • 1. Create a Wifip2pserviceinfo object.
    • 2. Fill in the information about the service.
    • 3. Call the Addlocalservice () method to complete the local Service registration.
     Private void startregistration() {//Create A string map containing information about your service.Map record =NewHashMap (); Record.put ("Listenport", string.valueof (Server_port)); Record.put ("Buddyname","John Doe"+ (int) (Math.random () * +)); Record.put ("Available","Visible");//Service information. Pass it an instance name, service type        //_protocol._transportlayer, and the map containing        //Information Other devices would 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'll be used to indicate success or failure of        //the request.Mmanager.addlocalservice (channel, ServiceInfo,NewActionListener () {@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(intARG0) {//Command failed. Check for p2p_unsupported, ERROR, or BUSY}        }); }
Search for nearby services

Android uses a callback method to notify the application that a service is available, so the first thing to do is set the callback. Create a Wifip2pmanager.dnssdtxtrecordlistener to listen for incoming records. This record is freely broadcast by other devices. When one of the records arrives, it copies the address of the device and other relevant information into an external data structure so that it can be accessed later. The following code assumes that the record contains a property of "buddyname" to identify the user.

Finalhashmap<string, string> buddies =NewHashmap<string, string> ();..Private void Discoverservice() {Dnssdtxtrecordlistener Txtlistener =NewDnssdtxtrecordlistener () {@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 obtain information about the service, you need to create a Wifip2pmanager.dnssdserviceresponselistener interface. This interface will receive the actual connection information. The map object in the preceding code snippet consists of a key-value pair with the address of the device and "Buddy name". The service response listener uses this feature to establish a connection to the DNS record. Once the two listeners have been implemented, add them to the Wifip2pmanager setdnssdresponselisteners () method.

Private void Discoverservice() {... Dnssdserviceresponselistener Servlistener =NewDnssdserviceresponselistener () {@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); ...}

The next step is to create a new service request and then call it as a parameter to the Addservicerequest () method, which also requires a listener to respond to success or failure.

 Servicerequest =        Wifip2pdnssdservicerequest.newinstance (); Mmanager.addservicerequest (channel, Servicerequest, new  Ac Tionlistener () { @Override  public  void  onsuccess  () {                    //success!  }  @Override  public
      void  onfailure  (  int  code) {//Command failed. Check for p2p_unsupported, ERROR, or BUSY }});  

Finally, call the Discoverservices () method to start the search service.

Mmanager.discoverservices (channel,NewActionListener () {@Override             Public void onsuccess() {//success!}@Override             Public void onfailure(intCode) {//Command failed. Check for p2p_unsupported, ERROR, or BUSY                if(Code = = wifip2pmanager.p2p_unsupported) {LOG.D (TAG,"Peer to Do" T supported on this device. ");Else if(...)        ...            } });

If all the above has been done, then you can shout Hallelujah and have completed all the steps. If you encounter a problem and look for the method that takes Wifip2pmanager.actionlistener as a parameter, this callback method tells the program whether it is a success or failure. If you want to work around this problem, put the debugging code in the OnFailure () method. The error code provided by the method will tell you where the problem is. The following are the possible error codes and their explanations:

p2p_unsupported

    当前设备不支持Wi-Fi P2P

BUSY

    系统处于繁忙处理状态

ERROR

    由于内部错误造成操作失败

Android Official Development Document Training Series Course Chinese version: Connect wireless devices via peer Search Network Service

Related Article

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.