Android Wear development-Data Communication-section II: Sending and receiving data

Source: Internet
Author: User
Tags unique id

This section consists of sending and receiving 3 kinds of data:
1.Data Items: Bit type data, limit within 100KB
2.Assets: Resource type data, no maximum size
3.Message: Send message, Trigger command

Http://developer.android.com/training/wearables/data-layer/data-items.html

1.Syncing Data Items

DataItem defines the data interface for synchronizing phones and watches. A DataItem object typically consists of the following 2 sections:

    • Payload: An array of bit types that supports any object that implements the serialized interface. The maximum load is 100KB.
    • Path: A unique string that must begin with a "/" slash, such as "/path/to/data"

In general, you do not need to implement the DataItem interface, but in the following ways:

    1. Creates a Putdatarequest object that is defined with a unique string ID.
    2. Call the SetData () method to pass load data into the
    3. Call the Dataapi.putdataitem () request system to build the data unit
    4. When a data unit is requested, the system returns an object that implements the DataItem interface

The above approach is not the best option and can be implemented in a datamap way, similar to bundles.

Sync data with a data Map

Because Datamap is implemented with bundles, it solves the problem of serialization and can manipulate the data using key-value pairs.

How to use
    1. Constructs a Putdatamaprequest object that sets a unique ID.
    2. Call Putdatamaprequest.getdatamap () to get a data map.
    3. With put ... () method to set the required data.
    4. Call Putdatamaprequest.asputdatarequest () to get a Putdatarequest object.
    5. Call Dataapi.putdataitem () to request the system to pass data.

Note: If the watch and phone are not connected, they will be cached on the sending side until the two ends are connected and then synchronized.
Code sample

Private void Syncdata () {    = putdatamaprequest.create ("/count");    Datamap.getdatamap (). Putint (Count_key, COUNT+ +)    ; = datamap.asputdatarequest ();    Pendingresult<DataApi.DataItemResult> pendingresult = wearable.dataapi        . Putdataitem ( Mgoogleapiclient, request);}
Listen for Data Item Events

When the data at either end changes, if you want to notify the other end, you can listen to the data to change the interface to achieve:

Code sample
@Override Public voidondatachanged (Dataeventbuffer dataevents) { for(dataeventEvent: 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 ()); }    }}

Http://developer.android.com/training/wearables/data-layer/assets.html

2.Transferring Assets

If you want to send a large binary block of data via Bluetooth, you need to bind the data to the asset object.

Assets automatically handles the data cache's blocking resend and saving the Bluetooth data bandwidth. A general-purpose mode to process the mobile app to download the picture, then process it into the appropriate size, and finally convert it to asset sent to the watch.

Note: The data unit is limited to 100KB, and assets is not limited. But the assets of transmitting big data will affect the user experience, so if you have to pass the larger assets, you need to test more.

Transfer an Asset

Assets is built, you can pass data in putdatarequest or Putdatamaprequest way

Putdatarequest:
Private void transferasset{    = Bitmapfactory.decoderesource (getresources (), r.drawable.image);     = Createassetfrombitmap (bitmap);     = Putdatarequest.create ("/image");    Request.putasset ("profileimage", asset);    Wearable.DataApi.putDataItem (mgoogleapiclient, request);   }
Putdatamaprequest:
Private voidtransferasset{Bitmap Bitmap=Bitmapfactory.decoderesource (Getresources (), r.drawable.image); Asset Asset=Createassetfrombitmap (bitmap); Putdatamaprequest DataMap= Putdatamaprequest.create ("/image"); Datamap.getdatamap (). Putasset ("Profileimage", Asset) Putdatarequest Request=datamap.asputdatarequest (); Pendingresult<DataApi.DataItemResult> Pendingresult =Wearable.dataapi. Putdataitem (mgoogleapiclient, request);}
Receive assets
@Override Public voidondatachanged (Dataeventbuffer dataevents) { for(dataeventEvent: dataevents) {    if(Event. GetType () = = Dataevent.type_changed &&Event. Getdataitem (). GetURI (). GetPath (). Equals ("/image") {Datamapitem Datamapitem= Datamapitem.fromdataitem (Event. Getdataitem ()); Asset Profileasset= Datamapitem.getdatamap (). Getasset ("Profileimage"); Bitmap Bitmap=Loadbitmapfromasset (Profileasset); //Do something with the bitmap    }  }} PublicBitmap Loadbitmapfromasset (Asset Asset) {if(Asset = =NULL) {        Throw NewIllegalArgumentException ("Asset must be Non-null"); } connectionresult result=Mgoogleapiclient.blockingconnect (Timeout_ms, timeunit.milliseconds); if(!result.issuccess ()) {        return NULL; }    //convert asset into a file descriptor and block until it 's readyInputStream Assetinputstream =Wearable.DataApi.getFdForAsset (mgoogleapiclient, asset).await(). getInputStream ();    Mgoogleapiclient.disconnect (); if(Assetinputstream = =NULL) {LOG.W (TAG,"requested an unknown Asset."); return NULL; }    //decode the stream into a bitmap    returnBitmapfactory.decodestream (Assetinputstream);}

Http://developer.android.com/training/wearables/data-layer/messages.html

3.Sending and Receiving Messages

The following two types of data can be sent via MESSAGEAPI:

    • Any type of data
    • Message actions with unique key-value pairs

Unlike the bidirectional synchronization of DataItem, the message is one-way. The message is sent to the other end through a one-way connection, which facilitates remote invocation (Rpc-remote procedure calls).

Send a Message

The following is a sample that sends a message to initiate activity, which blocks the thread until the message arrives or times out when the message is sent.

Node node;//The connected device to send the message togoogleapiclient mgoogleapiclient; Public StaticFinal Start_activity_path ="/start/mainactivity";... Sendmessageresult result=Wearable.MessageApi.sendMessage (mgoogleapiclient, node, Start_activity_path,NULL).await(); if(!result.getstatus (). issuccess ()) {LOG.E (TAG,"error:failed to send Message:"+result.getstatus ()); }

Here are the nodes that get all the connections to the Android Wear app.

Private Collection<string> getnodes () {    new hashset<string>();     =            Wearable.NodeApi.getConnectedNodes (mgoogleapiclient). await ();      for (Node node:nodes.getNodes ()) {        Results.add (Node.getid ());    }     return results;}
Receive a Message

The following is an example of receiving a message, corresponding to the example of the previous send message. You need to register the listener with Messageapi.addlistener () before you can process the received message. It is described in other chapters.

@Override  Public void onmessagereceived (messageevent messageevent) {    if  (Messageevent.getpath (). Equals (Start_ Activity_path) {        new Intent (this, mainactivity.  Class);        Startintent.addflags (intent.flag_activity_new_task);        StartActivity (startintent);    }}

Android Wear development-Data Communication-section II: Sending and receiving data

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.