Summary on the data synchronization mechanism between mobile phones and watches established by Android, and android Data Synchronization

Source: Internet
Author: User

Summary on the data synchronization mechanism between mobile phones and watches established by Android, and android Data Synchronization

Summary of Android Wear Data Synchronization Mechanism

After a Bluetooth connection is established between the mobile phone and the watch, data can be transmitted through Google Play Service.

Data Item

DataItem provides automatic synchronization between mobile phone and watch data storage. A DataItem object is determined by the URI composed of its creator and path. A DataItem object provides a data path for mobile phones and watches. developers can automatically synchronize data between mobile phones and watches by changing the specified DataItem.

Access data layer API

DataItem can store Data of mobile phones and watches. the operation of changing this object depends on the Data Layer API (the Data Layer APIs). That is to say, before changing DataItem Data, you must first access the data layer to obtain a GoogleApiClient instance so that you can use the data layer API.

The following code instantiates GoogleApiClient:

GoogleApiClient mGoogleAppiClient = new GoogleApiClient.Builder(this)        .addConnectionCallbacks(new ConnectionCallbacks() {               @Override               public void onConnected(Bundle connectionHint) {                   Log.d(TAG, "onConnected: " + connectionHint);                   // Now you 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 layer Api, you must call the connect () method. If the method is successful, the onConnected () method is called back. Otherwise, the onConnectionFailed () method is called back ().

Synchronize DataItems

After the GoogleApiClient connection is successful, you can synchronize data through DataItem.

A DataItem contains a link. One is Payload, which is a byte array. You can save the required data types and objects through serialization or deserialization. The other is Path, which is a unique string, different dataitems are different from each other starting with a backslash.

Generally, the DataMap class is used to implement the DataItem interface during development, similar to the Bundle key-Value Pair storage method.

The steps for using DataMap are as follows:

1. Create a PutDataMapRequest object and 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 DataItem.

If no connection is established between the phone and the watch at this time, the data will be stored in the Buffer, and will be sent to the other side after the next connection.

The following describes how to create a DataItem using DataMap.

PutDataMapRequest dataMap = PutDataMapRequest.create("/count");dataMap.getDataMap().putInt(COUNT_KEY, count++);PutDataRequest request = dataMap.asPutDataRequest();PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi        .putDataItem(mGoogleApiClient, request);

Listen to data layer events

Because the data layer synchronizes or sends data to the mobile phone and watch, you often need to know when DataItem is created and when the mobile phone and watch are connected or disconnected.

You can use two methods to listen to the data layer time. One is to inherit WearableListenerService, and the other is to implement DataApi. DataListener in the Activity. Regardless of the two methods, you can rewrite the required callback method to perform the corresponding operation.

1. Use WearableListenerService

This service can be used on both mobile phones and watches. This service is not applicable if one party does not need to listen to the data layer time.

For example, you can receive and set DataItem on the mobile phone end, implement the service on the watch end, listen to events at the data layer, and modify the watch UI.

WearableListenerService provides the callback interface onDataChanged () to handle DataItem changes. When DataItem is created, changed, or deleted, this event will be triggered on the mobile phone and watch.

The following describes how to use WearableListenerService.

1. Create a class to inherit WearableListenerService;

2. Listen for required events, such as onDataChanged ();

3. Declare An intentfilter in the configuration file to notify the system to listen to WearableListenerService. In this way, WearableListenerService is bound as required by the system.

The following code is a simple WearableListenerService implementation.

public class DataLayerListenerService extends WearableListenerService {    private static final String TAG = "DataLayerSample";    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)                .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 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 the intentfilter declared in the configuration file.

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

Use DataApi. DataListener to listen to the data layer

If you do not need the backend to listen for a long time, you can use DataApi. DataListener to listen. The following describes how to use this method.

1. Use the DataApi. DataListener Interface

2. Create GoogleApiClient in onCreate to access the data layer API

3. Call connect () in onStart to connect to Google PlayService

4. After connecting to GooglePlay Service, the system calls onConnected () to notify Google Play service that the activity listens to data layer events.

5. Call DataApi. removeListener () in onStop ()

6. Implement onDataChanged () callback

The following code uses DataApi. DataListener to listen to data layer events

public class MainActivity extends Activity implements        DataApi.DataListener, ConnectionCallbacks, OnConnectionFailedListener {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        mGoogleApiClient = new GoogleApiClient.Builder(this)                .addApi(Wearable.API)                .addConnectionCallbacks(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.getDataItem().getUri());            } else if (event.getType() == DataEvent.TYPE_CHANGED) {                 Log.d(TAG, "DataItem changed: " + event.getDataItem().getUri());            }        }    }

Get the mobile phone notification service

Android provides a service interface icationicationlistenerservice, which inherits the service and can obtain notifications initiated by apps on mobile phones. The following statements and permissions must be added to 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>  

In this way, an option is displayed in system settings to determine whether to allow the Service to capture notifications. In settings-security and privacy-Notification read permission

The Service has two abstract methods to implement. The callback method is triggered when a notification is initiated and the notification is destroyed.

public class NotificationCollectorService extends NotificationListenerService {        @Override      public void onNotificationPosted(StatusBarNotification sbn) {     }       @Override      public void onNotificationRemoved(StatusBarNotification sbn) {      }  }  

That is to say, when the system finds that an application generates a notification or the user deletes a notification, the two functions of the Service will be called back. The StatusBarNotification parameter of the function contains the specific information of the notification.

In Android Wear development, this method is used to capture notifications from the mobile phone and synchronize the notifications to the watch.

Notification Synchronization

The received notification is passed to the callback function onicationicationposted () in the form of a StatusBarNotification object (),

Call the common methods of StatusBarNotification objects to retrieve PackageName, Tag, Id, notification object, and PostTime in StatusBarNotification, and create DataItem with these values.



How to synchronize data on Android phones

You can use titanium backup copy to restore an archive.

What is the role of the Data Synchronization icon (the arrow at the beginning and end of the ring) in the Android mobile phone system? What is the impact of enabling or disabling data synchronization?

In fact, it is to upload data from your mobile phone to your fixed account on the internet server. In the future, if your mobile phone breaks down or is lost, You can submit your address book and other data from the internet server account. It is best not to close it. Otherwise, all data will be lost in the event of an accident,

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.