我有一个Android Wear应用程序,它将加速度计值传递给手持设备应用程序。
我想在手持设备应用程序中通知刚刚丢失与Android Wear应用程序的连接时(例如,当Android Wear应用程序关闭时)。
我该如何实现?
感谢您的帮助
答案 0 :(得分:1)
在磨损到设备网络中连接的设备称为节点。您可以使用Node API来确定设备何时进入或离开网络(例如,当磨损设备与手机断开连接时)。
https://developers.google.com/android/reference/com/google/android/gms/wearable/NodeApi.NodeListener
您还可以使用Node API在任何给定时间获取所有连接设备的列表(例如,连接到手机的所有磨损设备)
https://developers.google.com/android/reference/com/google/android/gms/wearable/NodeApi
答案 1 :(得分:0)
您可以通过扩展WearableListenerService并覆盖onConnectedNodes()方法轻松完成此操作。
可穿戴方
public class DisconnectListenerService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks {
/* the capability that the phone app would provide */
private static final String CONNECTION_STATUS_CAPABILITY_NAME = "is_connection_lost";
private GoogleApiClient mGoogleApiClient;
@Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.build();
}
@Override
public void onConnectedNodes(List<Node> connectedNodes) {
if (mGoogleApiClient.isConnected()) {
updateStatus();
} else if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
private void updateStatus() {
Wearable.CapabilityApi.getCapability(
mGoogleApiClient, CONNECTION_STATUS_CAPABILITY_NAME,
CapabilityApi.FILTER_REACHABLE).setResultCallback(
new ResultCallback<CapabilityApi.GetCapabilityResult>() {
@Override
public void onResult(CapabilityApi.GetCapabilityResult result) {
if (result.getStatus().isSuccess()) {
updateConnectionCapability(result.getCapability());
} else {
Log.e(TAG, "Failed to get capabilities, " + "status: " + result.getStatus().getStatusMessage());
}
}
});
}
private void updateConnectionCapability(CapabilityInfo capabilityInfo) {
Set<Node> connectedNodes = capabilityInfo.getNodes();
if (connectedNodes.isEmpty()) {
// The connection is lost !
} else {
for (Node node : connectedNodes) {
if (node.isNearby()) {
// The connection is OK !
}
}
}
}
@Override
public void onConnected(Bundle bundle) {
updateStatus();
}
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onDestroy() {
if (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()) {
mGoogleApiClient.disconnect();
}
super.onDestroy();
}
}
电话侧
在名为wear.xml的values /目录中创建一个xml文件
<resources>
<string-array name="android_wear_capabilities">
<item>is_connection_lost</item>
</string-array>
</resources>