Search code examples
androidandroid-servicewear-osgoogle-api-clientandroid-wear-data-api

android - service for interaction with wearable


I tried creating a service (which extends WearableListenerService) which should send as well as receive data with wearable. But when i created GoogleApiClient object in that service, it failed with NullPointerException.

public class MyService extends WearableListenerService{

    private GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addApi(Wearable.API)
        .build();
    private final String MESSAGE_PATH = "/message";
    private String remoteNodeId;


    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
         Log.d("myMessage",messageEvent.getData());
         remoteNodeId = messageEvent.getSourceNodeId();
         sendMessage("Content received");
    }

    public void sendMessage(String message) {

         Wearable.MessageApi.sendMessage(mGoogleApiClient,
                 remoteNodeId,MESSAGE_PATH,message.getBytes());
    }

}

Whenever I tried to run this program I am getting error message with a NullPointerException on mGoogleApiClient declaration part.


Solution

  • override onCreate in your Service, and put the initialization of mGoogleApiClient in it

    private GoogleApiClient mGoogleApiClient;
    
    public void onCreate() {
      super.onCreate();
      mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .build();
    }