android - service for interaction with wearable

121 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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();
}
0
On

Don't forget to call mGoogleApiClient.connect();