Android Wear development-data communication-Event handling

Source: Internet
Author: User
Tags call back

http://developer.android.com/training/wearables/data-layer/events.html#WaitSection 1:Wait for the Status of data Layer calls-to await the results of the operation

You'll notice that calls to the data layer API sometimes return a pendingresult, such as Putdataitem (). As soon as the Pendingresult is created, the operation are queued in the background. If you don't have else after this, the operation eventually completes silently. However, you'll usually want to does something with the result after the operation completes and so the Pendingresult lets you Wait for the result status, either synchronously or asynchronously.

In the case of data communication, sometimes a Pendingresult object is returned, for example, the Putdataitem method is called. Once the Pendingresult object is built, Then the data operation is in the background queue. You can choose whether to process the result of the operation. The Pendingresult object allows you to get the results of the operation, either synchronously or asynchronously.

Asynchronously waiting-Asynchronous wait

If your code is running on the main UI thread, does not making blocking calls to the data layer API. You can run the calls asynchronously by adding a callback to the Pendingresult object, and which fires when the operation is C Ompleted:

If you are doing data manipulation in the UI thread, be careful about blocking the problem. Here you can use callback snooping to implement asynchronous waits:

Pendingresult.setresultcallback (new resultcallback<dataitemresult>() {    @Override    Public void onresult (final  dataitemresult result) {        if( Result.getstatus (). Issuccess ()) {            "Data Item Set:" + Result.getdataitem (). GetURI ());}}    ); 

synchronously waiting-Synchronous wait

If your code is running on a separate handler thread in a background service (which are the case in a Wearablelistenerservi CE), it ' s fine for the calls to block. In this case, you can call await () on the Pendingresult object, which would block until the request has completed, and Retu RN a Result object:

If you perform data operations in a separate background service process, you can use synchronous waits to process the results of the operation and block the process until the results are obtained.

Dataitemresult result = pendingresult.await (); if (Result.getstatus (). Issuccess ()) {    "Data Item Set:" + Result.getdataitem (). GetURI ());}

Section 2:listen for data layer events-listen for the event

Because the data layer synchronizes and sends data across the handheld and wearable, you normally want-listen for Impor Tant events, such as when data items is created, messages is received, or when the wearable and handset is connected.

Because of the synchronization of data communication between the mobile phone and the watch, it is usually necessary to listen for some important events, such as data creation, message receiving, and communication connection.

To listen for data layer events, there are both options:

  1. Create a service that extends Wearablelistenerservice.
  2. Create an activity that implements Dataapi.datalistener.

With both these options, you override any of the data event callbacks that's about handling in your implementation.

Listen to data communication, can be implemented in the following two ways:

    1. Create a service that inherits from Wearablelistenerservice
    2. Create an activity that implements the Dataapi.datalistener data interface
1.With a Wearablelistenerservice

You typically create instances of this service in both your wearable and handheld apps. If you don't care about the data events in one of the these apps, then you don ' t need to implement the service in that particular App.
For example, can has a handheld app that's sets and gets data item objects and a wearable app that listens for these up Dates to update it ' s UI. The wearable never updates any of the data items, so the Handheld app doesn ' t listen for any data events from the wearable App.

Usage Scenarios

In general, a subclass service is built on both the mobile and the watch side. But if there is no need to listen for data events at any one end, there is no need to build them.

For example, you can build and pass data to your watch on your phone, and watch these data events to update your interface. But the watch side is only one-sided access to data, do not make any changes to the data, then the mobile phone side does not need to listen to data communication events.

You can listen for the following events with Wearablelistenerservice:

  • Ondatachanged ()-Called when data item objects is created, changed, or deleted. An event on one side of a connection triggers this callback on both sides.
  • Onmessagereceived ()-a message sent from one side of a connection triggers this callback in the other side of the Connect Ion.
  • Onpeerconnected () and onpeerdisconnected ()-Called when connection with the handheld or wearable are connected or Disconne Cted. Changes in connection state on one side of the connection triggers these callbacks on both sides of the connection.
Method Introduction

The next step is to introduce some important event methods for Wearablelistenerservice:

    • Ondatachanged (): Increase, delete, change, these three kinds of events will call this interface. And both ends will be triggered by the call. → Bidirectional
    • Onmessagereceived (): The message is sent from one end, and the interface at the other end is called. → Unidirectional
    • Onpeerconnected (), onpeerdisconnected (): Triggers when both ends are connected or disconnected. Changing the connection state at one end invokes the interface at both ends. → Bidirectional

To create a wearablelistenerservice:

  1. Create a class that extends Wearablelistenerservice.
  2. Listen for the events and that's about, such as ondatachanged ().
  3. Declare an intent filter on your Android manifest to notify the system is about your wearablelistenerservice. This allows the system to bind your service as needed.
Implementation steps
    1. Inherit Wearablelistenerservice
    2. Listening for data communication events
    3. Declare in manifest and add intent filter to listen Com.google.android.gms.wearable.BIND_LISTENER this action
Code sample
 Public classDatalayerlistenerserviceextendsWearablelistenerservice {Private Static FinalString TAG = "Datalayersample"; Private Static FinalString Start_activity_path = "/start-activity"; Private Static FinalString Data_item_received_path = "/data-item-received"; @Override Public voidondatachanged (Dataeventbuffer dataevents) {if(log.isloggable (tag, log.debug)) {log.d ( tag,"Ondatachanged:" +dataevents); }        FinalList events =freezableutils. freezeiterable (dataevents); Googleapiclient googleapiclient=NewGoogleapiclient.builder ( This). Addapi (WEARABLE.API). build (); Connectionresult Connectionresult=Googleapiclient.blockingconnect (30, Timeunit.seconds); if(!connectionresult.issuccess ()) {LOG.E (TAG,"Failed to connect to Googleapiclient."); return; }        //Loop through the events and send a message//To the node, that created the data item.         for(dataevent event:events) {URI Uri=Event.getdataitem (). GetURI (); //Get the node ID from the host value of the URIString nodeId =Uri.gethost (); //Set the data of the message to be the bytes of the URI.            byte[] Payload =uri.tostring (). GetBytes (); //Send the RPCWearable.MessageApi.sendMessage (googleapiclient, NodeId, Data_item_received_path, Paylo        AD); }    }}

Manifest statement

<service android:name= ". Datalayerlistenerservice ">  <intent-filter>      <action android:name=" Com.google.android.gms.wearable.BIND_LISTENER "/>  </intent-filter></service>

Permissions within Data Layer callbacks

In order to deliver callbacks to your application for data layer events, Google Play services binds to Yourwearablelistene Rservice, and calls your callbacks via IPC. This have the consequence that your callbacks inherit the permissions of the calling process.

If you try to perform a privileged operation within a callback, the security check fails because your callback is running With the identity of the calling process, instead of the identity of the your app ' s process.

To fix this, call Clearcallingidentity (), to reset identity after crossing the IPC boundary, and then restore identity WI Th restorecallingidentity () When you ' ve completed the privileged operation:

Watch out.

Permission issues in the data callback interface
To callback the data event interface, Google play binds your service and calls through the IPC. This also causes your callback interface to inherit the permissions of the calling process.
If you want to do some privileged operations in the callback interface, you will find that the security validation fails, and you will find that the process ID printed in the callback interface is the ID of the process that triggered the callback interface, not the process of your application.
To solve this problem, first call clearcallingidentity () to reset the ID, revert to the application process ID, perform the action you need, and then call back to the ID of the restorecallingidentity () caller.

long token = binder.clearcallingidentity (); Try {    finally  {    binder.restorecallingidentity (token);}

2.With a Listener Activity

If your app only cares on data layer events when the user is interacting with the app and does not need a long-running Service to handle every data change, can listen for events in a activity by implementing one or more of the following Interfaces

  • Dataapi.datalistener
  • Messageapi.messagelistener
  • Nodeapi.nodelistener
Method Introduction

If your application just needs to listen for data communication events while the user is open, without having to listen for data changes in the background, you can implement the following interfaces to achieve your needs.

    • Dataapi.datalistener
    • Messageapi.messagelistener
    • Nodeapi.nodelistener

To create a activity that listens for data events:

  1. Implement the desired interfaces.
  2. In OnCreate (Bundle), create a instance of Googleapiclient to work with the data layer API.
  3. In OnStart (), call Connect () to connect the client to Google Play services.
  4. When the connection-to-Google Play Services is established, the system calls onconnected (). This is where you call Dataapi.addlistener (), Messageapi.addlistener (), or Nodeapi.addlistener () to notify Google Play Ser Vices that your activity is interested in listening for data layer events.
  5. In OnStop (), unregister any listeners with Dataapi.removelistener (), Messageapi.removelistener (), or Nodeapi.removelistener ().
  6. Implement ondatachanged (), onmessagereceived (), onpeerconnected (), and onpeerdisconnected (), depending on the interfaces that implemented.
Implementation steps

The next step is to create an activity that listens for data communication events

    1. implementing Interfaces : Implementing the interfaces enumerated above (depending on the requirements, not all implementations)
    2. Create a Service object : Create a Googleapiclient object in the OnCreate method that implements the connection to the data communication.
    3. Connection Service : Call Googleapiclient's Connect method in the OnStart method to connect to the service
    4. Register Listener : When Googleapiclient is connected to the service, it will callback the Onconnected method, then we can register the listener here to listen to the communication events we are concerned about.
    5. Unregister the Listener and disconnect the service : In the OnStop method, unregister the listener before you register, and then disconnect the Googleapiclient service.
    6. implement the event callback interface : Implement interfaces based on registered listeners and handle related requirements.
Code sample

Here is a sample that implements the Dataapi.datalistener:

 Public classMainactivityextendsActivityImplementsDataapi.datalistener, Connectioncallbacks, Onconnectionfailedlistener {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); Mgoogleapiclient=NewGoogleapiclient.builder ( This). Addapi (WEARABLE.API). Addconnectioncallbacks ( This). Addonconnectionfailedlistener ( This). build (); } @Overrideprotected voidOnStart () {Super. OnStart (); if(!mresolvingerror)        {Mgoogleapiclient.connect (); }} @Override Public voidonconnected (Bundle connectionhint) {if(log.isloggable (tag, log.debug)) {log.d ( tag,"Connected to Google Api Service"); } Wearable.DataApi.addListener (Mgoogleapiclient, This); } @Overrideprotected voidOnStop () {if(NULL! = Mgoogleapiclient &&mgoogleapiclient.isconnected ()) {Wearable.DataApi.removeListener (mgoogleapiclient, This);        Mgoogleapiclient.disconnect (); }        Super. OnStop (); } @Override Public voidondatachanged (Dataeventbuffer dataevents) { for(dataevent event:dataevents) {if(Event.gettype () = =dataevent.type_deleted) {LOG.D (TAG,"DataItem deleted:" +Event.getdataitem (). GetURI ()); } Else if(Event.gettype () = =dataevent.type_changed) {LOG.D (TAG,"DataItem changed:" +Event.getdataitem (). GetURI ()); }        }    }

Android Wear development-data communication-Event handling

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.