我正在制作一个穿戴应用程序,它在启动应用程序主屏幕时从数据库(在手持设备上)获取数据。因此,当主页活动启动时,它会使用 Wearable.MessageApi.sendMessage 函数从 Android Wear 向手持设备发送一条消息。在手持设备上,我有 WearableListenerService,它在 onMessageReceived 函数中接收此消息并读取数据库。读取数据库后,它会发送 putDatamapRequest 给磨损。
现在在磨损方面,我有另一个 WearableListenerService。在此服务中,永远不会调用 onDataChanged() 函数。它有时会运行,到目前为止它运行了 2-3 次,否则它不会运行。这是非常随机的。此外,一旦在 Wear 端接收到数据,我设置了一个静态 Arraylist,用于在 Activity 中显示数据。但由于并不总是调用 onDataChanged 函数,它会给出空数组列表。
这是我声明服务的 Wear 应用程序的 AndroidManifest 文件:
<service
android:name="com.example.deals.DataListenerService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
这是我将消息从穿戴式设备发送到手持设备的代码:
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
@Override
public void onResult(NodeApi.GetConnectedNodesResult getConnectedNodesResult) {
if(!getConnectedNodesResult.getNodes().isEmpty())
{
node = getConnectedNodesResult.getNodes().get(0);
System.out.println("Connected: "+ node.getId());
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), FETCH_ALL_DEALS, null).setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
@Override
public void onResult(MessageApi.SendMessageResult sendMessageResult) {
if (!sendMessageResult.getStatus().isSuccess()) {
Log.e("Wear:", "ERROR: failed to send Message: " + sendMessageResult.getStatus());
}
else
System.out.println("success");
}
});
}
else
System.out.println("Wear not connected to Phone");
}
});
}
@Override
public void onConnectionSuspended(int i) {
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.v("Phone to wear connection failed", "onConnectionFailed: " + result);
}
})
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
这是我在手持设备上的 onMessageReceive 代码:
public void onMessageReceived(MessageEvent messageEvent) {
System.out.println("Message Received on Phone on launch of wear homepage");
if(messageEvent.getPath().equals(FETCH_ALL_DEALS)) {
sendSavedDeals(); //fetch from db and make a datamap object using PutDataRequest
System.out.println("Message Received on Phone on launch of wear homepage");
}
else {
System.out.println("Unable to recognise action for "+messageEvent.getPath());
}
}
现在在我的磨损方面,我有一个 WearableListenerService,但它的 onDataChanged 方法永远不会被调用。你能帮我解决这个问题吗?