Android build phone and watch data synchronization mechanism summary

Source: Internet
Author: User

Android Wear Data Synchronization mechanism summary

When the phone is connected to the watch, the data can be transferred via the Google Play service.

Synchronizing Data Objects

DataItem provides automatic synchronization of the phone to the watch data store, and a DataItem object is determined by the URI of the creator and path. A DataItem object provides a data path for mobile phones and watches, and developers automatically sync their phone and watch data by changing the specified DataItem.

Accessing the data-tier API

DataItem can provide the storage of mobile phone and watch data, and the manipulation of the object depends on the data Layer API (which is used), that is to say, before changing the DataItem data, we need to access the data layer to obtain a googleapiclient instance , enabling the use of data-tier APIs.

The following is the code that instantiates the Googleapiclient

Googleapiclient mgoogleappiclient = new Googleapiclient.builder (this)        . Addconnectioncallbacks (New Connectioncallbacks () {               @Override public               void onconnected (Bundle connectionhint) {                   log.d (TAG, " onconnected: "+ connectionhint);                   Now, canuse the data layer API               }               @Override public               void onconnectionsuspended (int cause) {                   LOG.D (TAG , "onconnectionsuspended:" + cause);               }        })        . Addonconnectionfailedlistener (New Onconnectionfailedlistener () {               @Override public               Void onconnectionfailed (connectionresult result) {                   log.d (TAG, "onconnectionfailed:" + result);               }            })        . Addapi (WEARABLE.API)        . Build ();

Before using the data-tier API, you need to call the Connect () method, or callback the onconnected () method if successful, or callback onconnectionfailed ().

Sync Dataitems

Once the Googleapiclient connection is successful, the data can be synchronized through the DataItem.

A DataItem consists of a single part, a payload, which is a byte array that can be serialized or deserialized to hold the required data types and objects, and the other is path, a unique string that starts with a backslash and distinguishes between different dataitem.

Typically, the Datamap class is used in the development process to implement the DataItem interface, similar to how bundle key-value pairs are stored.

Here are the Datamap steps to use:

1, create the Putdatamaprequest object, set the path value for DataItem;

2. Use put ... () method to set the required data for datamap;

3. Call Putdatamaprequest.asputdatarequest () to create the Putdatarequest object;

4. Call Dataapi.putdataitem () to request the system to create the DataItem.

If the phone and watch are not connected at this point, the data will be saved in buffer, and will be sent to the other party after the next connection.

Here's how to create a DataItem using Datamap

Putdatamaprequest DataMap = putdatamaprequest.create ("/count");d Atamap.getdatamap (). Putint (Count_key, count++); Putdatarequest request = Datamap.asputdatarequest (); pendingresult<dataapi.dataitemresult> Pendingresult = Wearable.dataapi        . Putdataitem (MGoogleApiClient, request);

Listening for data-tier events

Because the data layer synchronizes or sends data to the phone and watch, it is often necessary to know when DataItem was created and when the phone and watch were connected or disconnected.

Listening data layer time can be used in two ways, one is to inherit Wearablelistenerservice, and one is to implement Dataapi.datalistener in activity. Regardless of which of the two methods you use, you can override the callback method that you want to perform the appropriate action.

1. Using Wearablelistenerservice

The service can be used on both the phone and the watch side, and it may not be applicable if a party does not need to listen on the data layer.

For example, you can receive and set DataItem on the phone, and then implement the service on the watch side to listen for events on the data layer to modify the watch's UI.

Wearablelistenerservice provides callback interface ondatachanged () to handle changes in DataItem when DataItem is created, changed, or deleted, the event of the phone and watch will be triggered.

Here's how to use Wearablelistenerservice

1, create a class to inherit wearablelistenerservice;

2, listen to the necessary events, such as ondatachanged ();

3, in the configuration file to declare a INTENTFILTER notification system monitoring Wearablelistenerservice, so that when the system needs to bind Wearablelistenerservice.

The following code is a simple Wearablelistenerservice implementation.

public class Datalayerlistenerservice extends Wearablelistenerservice {private static final String TAG = "Datalayersam    Ple ";    private static final String Start_activity_path = "/start-activity";    private static final String Data_item_received_path = "/data-item-received";            @Override public void ondatachanged (Dataeventbuffer dataevents) {if (Log.isloggable (TAG, log.debug)) {        LOG.D (TAG, "ondatachanged:" + dataevents);        Final List events = freezableutils. freezeiterable (dataevents); Googleapiclient googleapiclient = new Googleapiclient.builder (this). Addapi (WEARABLE.API). b        Uild ();        Connectionresult Connectionresult = Googleapiclient.blockingconnect (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 URI String nodeId = Uri.gethost ();            Set the data of the message to be the bytes of the URI.            byte[] payload = uri.tostring (). GetBytes (); Send the RPC Wearable.MessageApi.sendMessage (googleapiclient, NodeId, Data_item_received_        PATH, payload); }    }}

The following code is declared in the configuration file Intentfilter

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

Using Dataapi.datalistener to monitor the data layer

If you do not need to listen for a long time in the background, you can use Dataapi.datalistener to listen, here is how to use this method.

1. Using Dataapi.datalistener interface

2. Create googleapiclientin OnCreate to access the data-tier API

3. Call connect () in OnStart for Google Playservice

4, but after connecting the GooglePlay service, the system calls onconnected (), notify Google Play service that activity listens to the data layer event

5. Call Dataapi.removelistener () in OnStop

6. Implement ondatachanged () callback

Here is the code that uses Dataapi.datalistener to listen for data-tier events

public class Mainactivity extends Activity implements Dataapi.datalistener, Connectioncallbacks, onconnectionfailed         Listener {@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main); Mgoogleapiclient = new Googleapiclient.builder (this). Addapi (WEARABLE.API). addconnectioncal    Lbacks (This). Addonconnectionfailedlistener (This). Build ();        } @Override protected void OnStart () {Super.onstart ();        if (!mresolvingerror) {mgoogleapiclient.connect ();            }} @Override public void onconnected (Bundle connectionhint) {if (Log.isloggable (TAG, log.debug)) {        LOG.D (TAG, "Connected to Google Api Service");    } Wearable.DataApi.addListener (Mgoogleapiclient, this); } @Override protected void OnStop () {if (null! = Mgoogleapiclient && mgoogleapicLient.isconnected ()) {Wearable.DataApi.removeListener (mgoogleapiclient, this);        Mgoogleapiclient.disconnect ();    } super.onstop ();            } @Override public void ondatachanged (Dataeventbuffer dataevents) {for (dataevent event:dataevents) { if (event.gettype () = = dataevent.type_deleted) {log.d (TAG, "DataItem DELETED:" + event.getd            Ataitem (). GetURI ()); } else if (event.gettype () = = dataevent.type_changed) {log.d (TAG, "DataItem CHANGED:" + event.getdataite            M (). GetURI ()); }        }    }

Get mobile phone notifications for everyone's service

Android provides a service class interface Notificationlistenerservice, which inherits the service, can get notifications from apps initiated in the phone, and needs to add the following declarations and permissions in the configuration file

<service android:name= ". Notificationlistener "           android:label=" @string/service_name "           android:permission=" Android.permission.BIND _notification_listener_service ">      <intent-filter>          <action android:name=" Android.service.notification.NotificationListenerService "/>      </intent-filter>  </service>  

This will show you the option to allow the service to capture notifications in the settings-Security and privacy-notification Read permission

The service has two abstract methods that need to be implemented, namely, when notification initiation and notification are destroyed, the callback method will be triggered.

public class Notificationcollectorservice extends Notificationlistenerservice {        @Override public      Void onnotificationposted (statusbarnotification SBN) {     }       @Override public      void Onnotificationremoved ( Statusbarnotification SBN) {      }  }  

This means that when the system discovers that an application generates a notification or the user deletes a notification, the service's two functions are called back, and the parameter statusbarnotification of the function contains specific information about the notification.

If it is in the Android Wear development, use this method to capture the phone's notifications, then sync to the watch, that is, using the service for transit.

Notification synchronization

The received notification is passed to the callback function onnotificationposted () in the form of a Statusbarnotification object.

Call the public method of the Statusbarnotification object to remove the PackageName, Tag, ID, notification object, and posttime from the statusbarnotification, respectively, Use these values to create DataItem.


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.