传输资源
编写:wly2014 - 原文: <http://developer.android.com/training/wearables/data-layer/assets.html>
为了通过蓝牙发送大量的二进制数据,比如图片,要将一个Asset附加到数据元上,并放入复制而来的数据库中。
Assets 能够自动地处理数据缓存以避免重复发送,保护蓝牙带宽。一般的模式是:手持设备下载图像,将图片压缩到适合在可穿戴设备上显示的大小,并以Asset传给可穿戴设备。下面的例子演示此模式。
Note: 尽管数据元的大小限制在100KB,但资源可以任意大。然而,传输大量资源会多方面地影响用户体验,因此,当传输大量资源时,要测试我们的应用以保证它有良好的用户体验。
传输资源
在Asset类中使用creat..()方法创建资源。下面,我们将一个bitmap转化为字节流,然后调用creatFromBytes()方法创建资源。
1. private static Asset createAssetFromBitmap(Bitmap bitmap) {
2. final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
3. bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
4. return Asset.createFromBytes(byteStream.toByteArray());
5. }
创建资源后,使用 DataMap 或者 PutDataRepuest 类中的 putAsset() 方法将其附加到数据元上,然后用 putDataItem() 方法将数据元放入数据库。
使用 PutDataRequest
1. Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
2. Asset asset = createAssetFromBitmap(bitmap);
3. PutDataRequest request = PutDataRequest.create("/image");
4. request.putAsset("profileImage", asset);
5. Wearable.DataApi.putDataItem(mGoogleApiClient, request);
使用 PutDataMapRequest
1. Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
2. Asset asset = createAssetFromBitmap(bitmap);
3. PutDataMapRequest dataMap = PutDataMapRequest.create("/image");
4. dataMap.getDataMap().putAsset("profileImage", asset)
5. PutDataRequest request = dataMap.asPutDataRequest();
6. PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi
7. .putDataItem(mGoogleApiClient, request);
接收资源
创建资源后,我们可能需要在另一连接端读取资源。以下是如何实现回调以发现资源变化和提取Asset对象。
1. @Override
2. public void onDataChanged(DataEventBuffer dataEvents) {
3. for (DataEvent event : dataEvents) {
4. if (event.getType() == DataEvent.TYPE_CHANGED &&
5. event.getDataItem().getUri().getPath().equals("/image")) {
6. DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
7. Asset profileAsset = dataMapItem.getDataMap().getAsset("profileImage");
8. Bitmap bitmap = loadBitmapFromAsset(profileAsset);
9. // Do something with the bitmap
10. }
11. }
12. }
14. public Bitmap loadBitmapFromAsset(Asset asset) {
15. if (asset == null) {
16. throw new IllegalArgumentException("Asset must be non-null");
17. }
18. ConnectionResult result =
19. mGoogleApiClient.blockingConnect(TIMEOUT_MS, TimeUnit.MILLISECONDS);
20. if (!result.isSuccess()) {
21. return null;
22. }
23. // convert asset into a file descriptor and block until it's ready
24. InputStream assetInputStream = Wearable.DataApi.getFdForAsset(
25. mGoogleApiClient, asset).await().getInputStream();
26. mGoogleApiClient.disconnect();
28. if (assetInputStream == null) {
29. Log.w(TAG, "Requested an unknown Asset.");
30. return null;
31. }
32. // decode the stream into a bitmap
33. return BitmapFactory.decodeStream(assetInputStream);
34. }
