"android app Development Technology: Network communications" Web Services discover how to use

Source: Internet
Author: User
<span id="Label3"></p><p><p>Guo Xiaoxing<br>Weibo: Guo Xiaoxing's Sina Weibo<br>Email:<span class="__cf_email__" data-cfemail="32535e5e575c45575e5e41720304011c515d5f">[email protected]</span><br>Blog: Http://blog.csdn.net/allenwells<br>Github:https://github.com/allenwells</p></p><p><p>Let us show you how to use the Android NSD service, the article will finally give the project source Code.</p></p>A registered NSD Service 1.1 Create a Nsdserviceinfo object<p><p>The Nsdserviceinfo object contains information that can help other devices decide whether to connect to the services we Provide.</p></p><p><p>We will set the following parameters for Nsdserviceinfo:</p></p> <ul> <ul> <li>ServiceName: the name of the service, which is visible to all devices in the local area network, in addition, the name in the network must be unique, and if duplicated, Android will automatically process, for example: there are two applications named nsdchat, One of them will be automatically converted to Nsdchat (1).</li> <li>Setvicetype: the service type, that is, the communication protocol used and the transport layer protocol, The syntax is "_protocol_transportlayer", for example: the network service is "_http._ctp", the printing service is "_ipp._tcp".</li> <li>Port: Port number, When you set the port number, you should try to avoid hard coding it in the code, to prevent conflicts with other Applications. The workaround is to not hardcode, using the next available port. Don't worry that other apps won't know the port number of the service, because that information will be included in the Service's broadcast Package. After receiving the broadcast, other apps will learn the service port number from the broadcast package and connect to your service via the Port.</li> </ul> </ul><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs cs"><span class="hljs-keyword">public</span><span class="hljs-keyword">void</span><span class="hljs-title">registerService</span>(<span class="hljs-keyword">int</span> port) { <span class="hljs-comment">// Create the NsdServiceInfo object, and populate it.</span> NsdServiceInfo serviceInfo <span class="hljs-keyword">new</span> NsdServiceInfo(); <span class="hljs-comment">// The name is subject to change based on conflicts</span> <span class="hljs-comment">// with other services advertised on the same network.</span> serviceInfo.setServiceName(<span class="hljs-string">"NsdChat"</span>); serviceInfo.setServiceType(<span class="hljs-string">"_http._tcp."</span>); serviceInfo.setPort(port); ....}</code></pre></pre>1.2 Registering the Registrationlistener interface<p><p>The Registrationlistener interface contains a series of callback functions registered with the Android system to notify the success and failure of application service registration/logoff.</p></p><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Initializeregistrationlistener</span></span>() {mregistrationlistener =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Nsdmanager.registrationlistener () {<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onserviceregistered</span></span>(nsdserviceinfo Nsdserviceinfo) {<span class="hljs-comment"><span class="hljs-comment">//Save the service Name. Android May has changed it in order</span> to</span> <span class="hljs-comment"><span class="hljs-comment">//resolve a conflict, so update the name initially requested</span></span> <span class="hljs-comment"><span class="hljs-comment">//with the name Android actually Used.</span></span>Mservicename = Nsdserviceinfo.getservicename (); }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onregistrationfailed</span></span>(nsdserviceinfo serviceinfo,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>ErrorCode) {<span class="hljs-comment"><span class="hljs-comment">//registration failed! Put Debugging code</span> here to determine Why.</span>}<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onserviceunregistered</span></span>(nsdserviceinfo Arg0) {<span class="hljs-comment"><span class="hljs-comment">//Service has been unregistered. </span>this is happens when</span> <span class="hljs-comment"><span class="hljs-comment">//nsdmanager.unregisterservice () and pass in this listener.</span></span>}<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onunregistrationfailed</span></span>(nsdserviceinfo serviceinfo,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>ErrorCode) {<span class="hljs-comment"><span class="hljs-comment">//unregistration Failed. Put Debugging code</span> here to determine Why.</span>} };}</code></pre>1.3 Calling the Registerservice () method to register the service<p><p>The Registerservice () method is an asynchronous method, so further operations need to be done in the onserviceregistered () method.</p></p><pre class="prettyprint"><pre class="prettyprint"><code class="hljs avrasm">public void Registerservice (int port) {nsdserviceinfo ServiceInfo = new Nsdserviceinfo () <span class="hljs-comment" ; < span> Serviceinfo<span class="hljs-preprocessor">.setservicename </span> (<span class="hljs-string"> "NsdChat" </span>) Span class= "hljs-comment"; </span> Serviceinfo<span class="hljs-preprocessor">.setservicetype </span> (<span class="hljs-string"> "_http._tcp." </span>) <span class="hljs-comment" ; < span> Serviceinfo<span class="hljs-preprocessor">.setport </span> (port) <span class="hljs-comment" ; < span> Mnsdmanager = Context<span class="hljs-preprocessor">.getsystemservice </span> (Context <span class="hljs-preprocessor" . nsd < span> _service) <span class="hljs-comment">; </span> Mnsdmanager<span class="hljs-preprocessor">.registerservice </span> (serviceinfo, nsdmanager<span class="HLJS-PR Eprocessor " . protocol < span> _dns_sd, mregistrationlistener) <span class="hljs-comment">; </span>} </span></span></span></span></code> </pre></pre>Service in two Discovery Networks 2.1 Configuring the Discovery Listener<p><p>The NSD API notifies the user program by using methods in the Interface:<br>-when to find the beginning<br>-when to discover failure<br>-when to find available services<br>-when Service is lost</p></p><p><p>In the code above, when an available service is found, The program makes the following checks:</p></p> <ol> <ol> <li>Compare the discovered service name with the local service, and determine whether the service found is native (this is legal).</li> <li>Check the type of service to see if it can be accessed.</li> <li>Check the name of the service and verify that the correct application is plugged IN.</li> </ol> </ol><p><p>We do not need to check the name of the service every time, only when you want to access a specific application, then to Judge. For example, the app only wants to communicate with the same app that runs on other Devices. however, if the application simply wants to connect to a network printer, then it is sufficient to see that the service type is "_ipp._tcp".</p></p><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Initializediscoverylistener</span></span>() {<span class="hljs-comment"><span class="hljs-comment">//instantiate a new Discoverylistener</span></span>Mdiscoverylistener =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Nsdmanager.discoverylistener () {<span class="hljs-comment"><span class="hljs-comment">//called as soon as service discovery Begins.</span></span> <span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">ondiscoverystarted</span></span>(String Regtype) {LOG.D (TAG,<span class="hljs-string"><span class="hljs-string">"Service Discovery started"</span></span>); }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Onservicefound</span></span>(nsdserviceinfo Service) {<span class="hljs-comment"><span class="hljs-comment">//A Service was found! Do something with it.</span></span>LOG.D (TAG,<span class="hljs-string"><span class="hljs-string">"Service Discovery success"</span></span>+ service);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(!service.getservicetype (). equals (service_type)) {<span class="hljs-comment"><span class="hljs-comment">//Service type is the string containing the protocol</span> and</span> <span class="hljs-comment"><span class="hljs-comment">//transport layer for this service.</span></span>LOG.D (TAG,<span class="hljs-string"><span class="hljs-string">"Unknown Service Type:"</span></span>+ Service.getservicetype ()); }<span class="hljs-keyword"><span class="hljs-keyword">Else</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(service.getservicename (). equals (mservicename)) {<span class="hljs-comment"><span class="hljs-comment">//the name of the service tells the user what they ' d</span> is</span> <span class="hljs-comment"><span class="hljs-comment">//connecting To. It could be "Bob's Chat App".</span></span>LOG.D (TAG,<span class="hljs-string"><span class="hljs-string">"same machine:"</span></span>+ mservicename); }<span class="hljs-keyword"><span class="hljs-keyword">Else</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(service.getservicename (). contains (<span class="hljs-string"><span class="hljs-string">"nsdchat"</span></span>) {mnsdmanager.resolveservice (service, mresolvelistener); } }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Onservicelost</span></span>(nsdserviceinfo Service) {<span class="hljs-comment"><span class="hljs-comment">//when The Network service is no longer available.</span></span> <span class="hljs-comment"><span class="hljs-comment">//Internal Bookkeeping code goes here.</span></span>LOG.E (TAG,<span class="hljs-string"><span class="hljs-string">"service lost"</span></span>+ service); }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">ondiscoverystopped</span></span>(String Servicetype) {LOG.I (TAG,<span class="hljs-string"><span class="hljs-string">"Discovery stopped:"</span></span>+ servicetype); }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onstartdiscoveryfailed</span></span>(String servicetype,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>ErrorCode) {LOG.E (TAG,<span class="hljs-string"><span class="hljs-string">"Discovery failed:error code:"</span></span>+ errorCode); Mnsdmanager.stopservicediscovery (<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>); }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onstopdiscoveryfailed</span></span>(String servicetype,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>ErrorCode) {LOG.E (TAG,<span class="hljs-string"><span class="hljs-string">"Discovery failed:error code:"</span></span>+ errorCode); Mnsdmanager.stopservicediscovery (<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>); } };}</code></pre>2.2 Starting the Discovery service<p><p>Once we have configured the discovery callback function, we can call the Discoverservice () function, which includes the type of service you are trying to discover, the protocol you are using, and the listener you created in the previous Step.</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs avrasm">mNsdManager<span class="hljs-preprocessor">.discoverServices</span>( SERVICE_TYPE, NsdManager<span class="hljs-preprocessor">.PROTOCOL</span>_DNS_SD, mDiscoveryListener)<span class="hljs-comment">;</span></code></pre></pre>Three connections to the In-network Service 3.1 Confirm the connection information of the service<p><p>When discovering network services that can be accessed online, call the Resolveservice () method, The Nsdmanager.relolvelistener object and the Nsdserviceinfo object obtained in the service discovery process are introduced, and the connection information can be parsed from the Nsdserviceinfo Object.</p></p><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Initializeresolvelistener</span></span>() {mresolvelistener =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Nsdmanager.resolvelistener () {<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onresolvefailed</span></span>(nsdserviceinfo serviceinfo,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>ErrorCode) {<span class="hljs-comment"><span class="hljs-comment">//called when the resolve Fails. Use the error code to Debug.</span></span>LOG.E (TAG,<span class="hljs-string"><span class="hljs-string">"Resolve failed"</span></span>+ errorCode); }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onserviceresolved</span></span>(nsdserviceinfo Serviceinfo) {LOG.E (TAG,<span class="hljs-string"><span class="hljs-string">"Resolve succeeded."</span></span>+ serviceinfo);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(serviceinfo.getservicename (). equals (mservicename)) {LOG.D (TAG,<span class="hljs-string"><span class="hljs-string">"same IP."</span></span>);<span class="hljs-keyword"><span class="hljs-keyword">return</span></span>; } Mservice = serviceinfo;<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Port = Mservice.getport (); InetAddress host = Mservice.gethost (); } };}</code></pre>Logout service on four program exits<p><p>It is critical that the NSD service is properly turned on and off during the lifetime of the Application. Unregistering the service when the program exits prevents other programs from repeatedly trying to connect because they do not know the service Exits. In addition, service discovery is a costly operation that should be stopped as the parent activity pauses and then turned on when the user returns to the Interface. therefore, we should reload the Activity's life cycle function and correctly manipulate the broadcast and discovery of the Service.</p></p><pre class="prettyprint"><code class=" hljs java"><span class="hljs-comment"><span class="hljs-comment">//in Your application ' s Activity</span></span> <span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword">protected</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">OnPause</span></span>() {<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(mnsdhelper! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {mnsdhelper.teardown (); }<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>. OnPause (); }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword">protected</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Onresume</span></span>() {<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>. Onresume ();<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(mnsdhelper! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {mnsdhelper.registerservice (mconnection.getlocalport ()); Mnsdhelper.discoverservices (); } }<span class="hljs-annotation"><span class="hljs-annotation">@Override</span></span> <span class="hljs-keyword"><span class="hljs-keyword">protected</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">OnDestroy</span></span>() {mnsdhelper.teardown (); Mconnection.teardown ();<span class="hljs-keyword"><span class="hljs-keyword">Super</span></span>. OnDestroy (); }<span class="hljs-comment"><span class="hljs-comment">//nsdhelper ' s TearDown method</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">TearDown</span></span>() {mnsdmanager.unregisterservice (mregistrationlistener); Mnsdmanager.stopservicediscovery (mdiscoverylistener); }</code></pre>Appendix<p><p>Nsdchat Project Source code download</p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: When we seriously to do one thing, we can find the endless fun, colorful technology like the scenery on the road, while walking to Appreciate.</p></p> <p><p>"android app Development Technology: Network communications" Web Services discover how to use</p></p></span>

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.