Pebble手表在连接/断开连接时会发送全局意图(Intent),这使得手机应用程序可以知道手表是否已连接。我已经搜索过了,但是我无法找到类似Android Wear的功能信息。如何知道可穿戴设备是否已连接到手机?是否可能像Pebble一样接收事件?谢谢。
getConnectedNodes
来获取已连接到此设备的节点列表。或者,您可以使用addListener(GoogleApiClient client, NodeApi.NodeListener listener)
注册一个监听器以接收所有节点事件。然后,您可以使用NodeApi.NodeListener
的回调函数。onPeerConnected(Node peer) and onPeerDisconnected(Node peer)
就像akmal所说的,您可以获取与手机连接的设备,但要知道当前手持设备是否与可穿戴设备连接
List<Node> connectedNodes =
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await().getNodes();
Node{Moto 360 6BBF, id=3b6d19bf, hops=1, isNearby=true}
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();
}
}
手机端
在 values/ 目录下创建一个名为 wear.xml 的 xml 文件。
<resources>
<string-array name="android_wear_capabilities">
<item>is_connection_lost</item>
</string-array>
</resources>
更多信息,请查看我在Stack Overflow问题中的解决方案。