我尝试创建一个服务(扩展WearableListenerService),该服务应该发送以及使用wearable接收数据。 但是当我在该服务中创建GoogleApiClient对象时,它失败并出现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());
}
}
每当我尝试运行此程序时,我都会收到NullPointerException
声明部分mGoogleApiClient
的错误消息。
答案 0 :(得分:0)
覆盖Service
中的onCreate,并在其中初始化mGoogleApiClient
private GoogleApiClient mGoogleApiClient;
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
}
答案 1 :(得分:0)
不要忘记致电mGoogleApiClient.connect();