Android Wear Bitmap DataItem资产大小

时间:2014-07-18 23:13:45

标签: android wear-os android-wear-data-api

我将Bitmap存储在Asset中,使用与我的可穿戴设备同步的DataItem存储在DataItemMap中。如果我使用:

遍历我的所有DataItem
DataItemBuffer list = api.getDataItems(connection.getClient()).await()
for(DataItem item : list) {
    ...
}

如何获得每个Asset的大小?

编辑:当我使用

DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset(BITMAP_KEY);
int size = asset.getData().length;

我得到的NPE说:

  

尝试获取null数组的长度

Asset使用了:

PutDataMapRequest putRequest = PutDataMapRequest.create(path);
DataMap map = putRequest.getDataMap();

ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.flush();
Asset asset = Asset.createFromBytes(stream.toByteArray());
map.putAsset(mapKey, asset);

Wearable.DataApi.putDataItem(connection.getClient(), putRequest.asPutDataRequest());

2 个答案:

答案 0 :(得分:3)

根据this,您必须通过DataApi读取资产:

GoogleApiClient client = ...;
PendingResult<DataApi.GetFdForAssetResult> pendingResult = Wearable.DataApi.getFdForAsset(client, asset);
DataApi.GetFdForAssetResult assetResult = pendingResult.await();
InputStream assetInputStream = assetResult.getInputStream();

修改 如果您只需要大小,请不要依赖资产。在发送方,只需将大小写入DataMap:

PutDataMapRequest putRequest = PutDataMapRequest.create(path);
DataMap map = putRequest.getDataMap();

ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.flush();
byte[] byteArray = stream.toByteArray();
Asset asset = Asset.createFromBytes(byteArray);
map.putAsset(mapKey, asset);
map.putLong("dataSize", byteArray.length);

Wearable.DataApi.putDataItem(connection.getClient(), putRequest.asPutDataRequest());

如果您想阅读尺寸,请执行以下操作:

DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
long size = dataMapItem.getDataMap().getLong("dataSize");

答案 1 :(得分:-1)

您似乎正在将资产添加到错误的地图中。你正在做什么&#34; putRequest.asPutDataRequest&#34;而不是&#34; map.asPutDataRequest&#34;。这样做:

PutDataMapRequest putRequest = PutDataMapRequest.create(path);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.flush();
Asset asset = Asset.createFromBytes(stream.toByteArray());
putRequest.putAsset(mapKey, asset);

Wearable.DataApi.putDataItem(connection.getClient(), putRequest.asPutDataRequest());

那你就不应该再拿NPE了。