Search code examples
javaandroidwear-osandroid-wear-data-api

Share objects from phone to android wear


I created an app. Within this app, you have objects which contains 2 strings (name and age) and a bitmap (avatar). Everything is saved to a sqlite database.

Now I want these objects to be accessible on my smart watch. So I want to achieve that you can go to start, start the application and scroll to the left and right to see these objects.

This means I have to retrieve the objects from the phone and get them at the watch.

I am currently wondering if I did everything right, or that I should do stuff differently. Whenever you start the application on your watch, I am sending a request to the phone that I want the objects.

private void sendMessage() {
    if(mGoogleApiClient.isConnected()) {
        new Thread( new Runnable() {
            @Override
            public void run() {
                NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( mGoogleApiClient ).await();
                for(Node node : nodes.getNodes()) {
                   Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), REQUEST_PET_RETRIEVAL_PATH, null).await();
                }
            }
        }).start();
    }
}

On the phone, I am receiving this message and sending a message back with an object.

public void onMessageReceived(MessageEvent messageEvent) {
    super.onMessageReceived(messageEvent);

    if (messageEvent.getPath().equals(REQUEST_PET_RETRIEVAL_PATH)) {


        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(Bundle connectionHint) {
                        final PutDataMapRequest putRequest = PutDataMapRequest.create("/send-pets");
                        final DataMap map = putRequest.getDataMap();

                        File imgFile = new File(obj.getAvatar());

                        Bitmap avatar;
                        if(imgFile.exists()) {
                            avatar = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                        } else {
                            avatar = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
                        }

                        Asset asset = createAssetFromBitmap(avatar);
                        map.putAsset("avatar", asset);
                        map.putString("name", obj.getName());
                        map.putString("age", obj.getDateOfBirth());
                        Wearable.DataApi.putDataItem(mGoogleApiClient, putRequest.asPutDataRequest());
                    }

                    @Override
                    public void onConnectionSuspended(int cause) {
                    }
                })
                .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(ConnectionResult result) {
                    }
                })
                .addApi(Wearable.API)
                .build();
        mGoogleApiClient.connect();
    }

On the watch, I am then retrieving the object.

public void onDataChanged(DataEventBuffer dataEvents) {
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    for(DataEvent event : events) {
        final Uri uri = event.getDataItem().getUri();
        final String path = uri!=null ? uri.getPath() : null;
        if("/send-pets".equals(path)) {
            final DataMap map = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
            String name = map.getString("name");
            String age = map.getString("age");

            Asset avatar = map.getAsset("avatar");
            Bitmap bitmap = loadBitmapFromAsset(avatar);
        }
    }
}

Now I am stuck with 2 questions:

1) Is this the way to go or should I solve it differently?

2) Is it possible to sent multiple objects at once or do I just have to put a loop around the part in the "onConnected" method and sent each object separatly?


Solution

  • Yes, this approach is good and correct one.

    Yes it is possible to send multiple but you should be aware that they are not "send" they are more something like shared or synchronized between phone and Wear, and can be modified in any further point in time (however I would recommend to save them to SharedPreferences on Wear to be able to access them in offline mode.

    So Message API sends objects (fast, and simple), and DataItem API is more complex but is used for bigger data and to share things between watch and phone.