Search code examples
androidwear-os

How to pass a Bundle to Android Wear using MessageApi


I'm currently passing Bytes to AnroidWear using:

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

I want to send a proper Data Bundle to my Wearable, how do I do that?


Solution

  • Convert your bundle to bytes, and on receiver, convert bytes to Bundle.

    With this simple method, you can send only String Bundle values.

    (And, It seems that you can convert Bundle to String with GSON and BundleTypeAdapterFactory also, but I'm not tested.)

    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;
    }