如何使用Android Wear的DataItem [英] How to use DataItem of Android Wear

查看:106
本文介绍了如何使用Android Wear的DataItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在手持设备和可穿戴设备之间同步首选项。我在手持式应用程序上实现了示例代码

I want to sync preference between handhelds and wearables. I implement sample code on handheld app.

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

然后在可穿戴应用程序上实现以下代码。但是保存的计数无法检索。

And then implement below code on wearable app. But saved count can't be retrieved.

 PutDataMapRequest dataMap = PutDataMapRequest.create("/count");
 int count = dataMap.getDataMap().getInt("COUNT_KEY");
 System.out.println(count);//print 0

我实际尝试过android手持设备和Android Wear模拟器。我确认使用Android Wear应用程序的演示卡将它们连接起来。

I tried in actual android handheld device and emulator of Android wear. I confirmed they are connected by using demo cards of Android Wear app.

我需要更多还是我误会了什么?

What I need more or do I misunderstand something?

推荐答案

使用该代码,您试图创建一个第二次放置请求,而不读取先前存储的数据。这就是为什么它为空的原因。

With that code, you are trying to create a second put request, not reading the previously stored data. That's why it's empty.

访问以前存储的数据的方法是使用 DataApi 方法。例如,您可以使用 Wearable.DataApi.getDataItems()获取所有存储的数据:

The way to access previously stored data is with the DataApi methods. For example, you can get all stored data with Wearable.DataApi.getDataItems():

PendingResult<DataItemBuffer> results = Wearable.DataApi.getDataItems(mGoogleApiClient);
results.setResultCallback(new ResultCallback<DataItemBuffer>() {
    @Override
    public void onResult(DataItemBuffer dataItems) {
        if (dataItems.getCount() != 0) {
            DataMapItem dataMapItem = DataMapItem.fromDataItem(dataItems.get(0));

            // This should read the correct value.
            int value = dataMapItem.getDataMap().getInt(COUNT_KEY);
        }

        dataItems.release();
    }
});

我已经使用了它并且有效。但是,我自己遇到了问题,因为我不知道Uri通过 Wearable.DataApi.getDataItem()的数据项c>。所以我发布了这个问题。如果您只是进行测试,则 DataApi.getDataItems()就足够了。

I've used this and it works. However, I'm having a problem myself, as I don't know the Uri to access a specific data item with Wearable.DataApi.getDataItem(). So I posted this question. If you're just testing though, DataApi.getDataItems() should suffice.

另一种选择是使用< a href = http://developer.android.com/reference/com/google/android/gms/wearable/DataApi.html#addListener%28com.google.android.gms.common.api.GoogleApiClient,%20com.google .android.gms.wearable.DataApi.DataListener%29 rel = nofollow noreferrer> DataApi.addListener() 通知存储更改

Another option is to use DataApi.addListener() to be notified of changes to the storage.

这篇关于如何使用Android Wear的DataItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆