如何使用MessageApi将Bundle传递给Android Wear

时间:2017-11-17 03:47:32

标签: android wear-os

我目前正在使用以下方式将Bytes传递给AnroidWear:

 MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
                        mGoogleApiClient, node.getId(), path, text.getBytes() ).await();

我想向我的可穿戴设备发送一个合适的数据包,我该怎么做?

1 个答案:

答案 0 :(得分:1)

将您的包转换为字节,并在接收器上将字节转换为Bundle。

使用此简单方法,您只能发送字符串捆绑值。

(并且,似乎你可以将Bundle转换为带有GSON和BundleTypeAdapterFactory的String,但我没有经过测试。)

public void example() {
    // Value
    Bundle inBundle = new Bundle();
    inBundle.putString("key1", "value");
    inBundle.putInt("key2", 1); // will be failed
    inBundle.putFloat("key3", 0.5f); // will be failed
    inBundle.putString("key4", "this is key4");

    // From Bundle to bytes
    byte[] inBytes = bundleToBytes(inBundle);

    // From bytes to Bundle
    Bundle outBundle = jsonStringToBundle(new String(inBytes));

    // Check values
    String value1 = outBundle.getString("key1"); // good
    int value2 = outBundle.getInt("key2"); // fail
    float value3 = outBundle.getFloat("key3"); // fail
    String value4 = outBundle.getString("key4"); // good

}


private byte[] bundleToBytes(Bundle inBundle) {
    JSONObject json = new JSONObject();
    Set<String> keys = inBundle.keySet();
    for (String key : keys) {
        try {
            json.put(key, inBundle.get(key));
        } catch (JSONException e) {
            //Handle exception here
        }
    }

    return json.toString().getBytes();
}


public static Bundle jsonStringToBundle(String jsonString) {
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        return jsonToBundle(jsonObject);
    } catch (JSONException ignored) {

    }
    return null;
}

public static Bundle jsonToBundle(JSONObject jsonObject) throws JSONException {
    Bundle bundle = new Bundle();
    Iterator iter = jsonObject.keys();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        String value = jsonObject.getString(key);
        bundle.putString(key, value);
    }
    return bundle;
}