When developing Android Wear programs, it is often necessary to transfer pictures via assets bluetooth.
1. Create asset, use create ... () method, such as passing a bitmap transmission as follows
private static Asset Createassetfrombitmap (Bitmap Bitmap) { final bytearrayoutputstream bytestream = new Bytearrayoutputstream (); Bitmap.compress (Bitmap.CompressFormat.PNG, bytestream); Return Asset.createfrombytes (Bytestream.tobytearray ());}
The asset is created and you need to point it to a data item by using the Putasset () method as follows
Using putdatarequest
Bitmap Bitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.image); Asset Asset = Createassetfrombitmap (bitmap); Putdatarequest request = Putdatarequest.create ("/image"); Request.putasset ("Profileimage", asset); Wearable.DataApi.putDataItem (mgoogleapiclient, request);
Useputdatamaprequest
Bitmap Bitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.image); Asset Asset = Createassetfrombitmap (bitmap); Putdatarequest request = Putdatarequest.create ("/image"); Request.putasset ("Profileimage", asset); Wearable.DataApi.putDataItem (mgoogleapiclient, request);
Useputdatamaprequest
Bitmap Bitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.image); Asset Asset = Createassetfrombitmap (bitmap); Putdatamaprequest DataMap = putdatamaprequest.create ("/image");d Atamap.getdatamap (). Putasset ("Profileimage", asset ) Putdatarequest request = Datamap.asputdatarequest (); pendingresult<dataapi.dataitemresult> Pendingresult = Wearable.dataapi . Putdataitem (MGoogleApiClient, request);
2. Watch-End receiving asset
@Overridepublic void ondatachanged (Dataeventbuffer dataevents) {for (dataevent event:dataevents) {if (Event.gettyp E () = = dataevent.type_changed && event.getdataitem (). GetURI (). GetPath (). Equals ("/image")) {Datamapite M datamapitem = Datamapitem.fromdataitem (Event.getdataitem ()); Asset Profileasset = Datamapitem.getdatamap (). Getasset ("Profileimage"); Bitmap Bitmap = Loadbitmapfromasset (Profileasset); Do something with the bitmap}}}public bitmap Loadbitmapfromasset (Asset Asset) {if (Asset = = null) {th Row new IllegalArgumentException ("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 ready inputstream 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 return Bitmapfactory.decodestream (Assetinputstream);}
In mobile phone with wearable device wearable Bluetooth Bluetooth pass assets (picture, etc.)