Skip to content Skip to sidebar Skip to footer

Sending Data From An Activity To Wearablelistenerservice

When I read about communication between an Activity and Service, I found that we can use either IBinder Messenger AIDL I am interested in the first two. So when I tried implemen

Solution 1:

After some digging, I found the solution. Hope it helps somebody else.

We can send message from an Activity to WearableListenerService using Wearable.MessageApi functions. When the Activity and WearableListenerService are on the same Node (device), we need to get the instance of the local node (current node from which the message is sent) for sending the message as below

NodeApi.GetLocalNodeResult nodes = Wearable.NodeApi.getLocalNode(mGoogleApiClient).await();

rather than

NodeApi.GetConnectedNodesResult nodes  = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();

which is used to get the list of other devices (such as wear) connected to the phone.

So, I was able to successfully send a message from my Activity to WearableListenerService as follows

Activity Code

publicclassPhoneActivityextendsActivityimplementsGoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

    privatestatic final StringTAG = "PhoneActivity";

    publicstatic final StringCONFIG_START = "config/start";
    publicstatic final StringCONFIG_STOP= "config/stop"Intent intent;
    TextView txtview;

    GoogleApiClient mGoogleApiClient;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone);

        if(null == mGoogleApiClient) {
            mGoogleApiClient = newGoogleApiClient.Builder(this)
                    .addApi(Wearable.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            Log.v(TAG, "GoogleApiClient created");
        }

        if(!mGoogleApiClient.isConnected()){
            mGoogleApiClient.connect();
            Log.v(TAG, "Connecting to GoogleApiClient..");
        }

        startService(newIntent(this, PhoneService.class));
    }

    @OverridepublicvoidonConnectionSuspended(int cause) {
        Log.v(TAG,"onConnectionSuspended called");
    }

    @OverridepublicvoidonConnectionFailed(ConnectionResult connectionResult) {
        Log.v(TAG,"onConnectionFailed called");
    }

    @OverridepublicvoidonConnected(Bundle connectionHint) {
        Log.v(TAG,"onConnected called");
    }

    @OverrideprotectedvoidonStart() {
        super.onStart();
        Log.v(TAG, "onStart called");
    }

    @OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.phone, menu);
        returntrue;
    }

    @OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_start_) {
            newSendActivityPhoneMessage(CONFIG_START,"").start();
        }elseif (id == R.id.action__stop) {
            newSendActivityPhoneMessage(CONFIG_STOP,"").start();
        }elseif (id == R.id.action_settings) {
            returntrue;
        }
        returnsuper.onOptionsItemSelected(item);
    }

    classSendActivityPhoneMessageextendsThread {
        String path;
        String message;

        // Constructor to send a message to the data layerSendActivityPhoneMessage(String p, String msg) {
            path = p;
            message = msg;
        }

        publicvoidrun() {
            NodeApi.GetLocalNodeResult nodes = Wearable.NodeApi.getLocalNode(mGoogleApiClient).await();
            Node node = nodes.getNode();
            Log.v(TAG, "Activity Node is : "+node.getId()+ " - " + node.getDisplayName());
            MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), path, message.getBytes()).await();
            if (result.getStatus().isSuccess()) {
                Log.v(TAG, "Activity Message: {" + message + "} sent to: " + node.getDisplayName());
            }
            else {
                // Log an errorLog.v(TAG, "ERROR: failed to send Activity Message");
            }
        }
    }
}

Service Code

publicclassPhoneServiceextendsWearableListenerServiceimplementsGoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

    privatestatic final StringTAG = "PhoneService";

    publicstatic final StringCONFIG_START = "config/start";
    publicstatic final StringCONFIG_STOP = "config/stop";

    GoogleApiClient mGoogleApiClient;

    publicPhoneService() {
    }

    @OverridepublicvoidonCreate() {
        super.onCreate();
        Log.v(TAG, "Created");

        if(null == mGoogleApiClient) {
            mGoogleApiClient = newGoogleApiClient.Builder(this)
                    .addApi(Wearable.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            Log.v(TAG, "GoogleApiClient created");
        }

        if(!mGoogleApiClient.isConnected()){
            mGoogleApiClient.connect();
            Log.v(TAG, "Connecting to GoogleApiClient..");
        }
    }

    @OverridepublicvoidonDestroy() {

        Log.v(TAG, "Destroyed");

        if(null != mGoogleApiClient){
            if(mGoogleApiClient.isConnected()){
                mGoogleApiClient.disconnect();
                Log.v(TAG, "GoogleApiClient disconnected");
            }
        }

        super.onDestroy();
    }

    @OverridepublicvoidonConnectionSuspended(int cause) {
        Log.v(TAG,"onConnectionSuspended called");
    }

    @OverridepublicvoidonConnectionFailed(ConnectionResult connectionResult) {
        Log.v(TAG,"onConnectionFailed called");
    }

    @OverridepublicvoidonConnected(Bundle connectionHint) {
        Log.v(TAG,"onConnected called");

    }

    @OverridepublicvoidonDataChanged(DataEventBuffer dataEvents) {
        super.onDataChanged(dataEvents);
        Log.v(TAG, "Data Changed");
    }

    @OverridepublicvoidonMessageReceived(MessageEvent messageEvent) {
        super.onMessageReceived(messageEvent);
        if(messageEvent.getPath().equals(CONFIG_START)){
            //do something here
        }elseif(messageEvent.getPath().equals(CONFIG_STOP)){
            //do something here
        }
    }

    @OverridepublicvoidonPeerConnected(Node peer) {
        super.onPeerConnected(peer);
        Log.v(TAG, "Peer Connected " + peer.getDisplayName());
    }

    @OverridepublicvoidonPeerDisconnected(Node peer) {
        super.onPeerDisconnected(peer);
        Log.v(TAG, "Peer Disconnected " + peer.getDisplayName());
    }
}

Post a Comment for "Sending Data From An Activity To Wearablelistenerservice"