2014-10-09 169 views
2

我有一個Android Wear應用程序,它將加速度計值傳遞給Handheld應用程序。Android Wear斷開連接通知

我想在手機應用程序中通知與Android Wear應用程序的連接剛剛丟失(例如Android Wear應用程序關閉時)。

我該如何執行該操作?

感謝您的幫助

回答

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

手機端

創造價值/目錄下的xml文件名爲wear.xml

<resources> 
    <string-array name="android_wear_capabilities"> 
     <item>is_connection_lost</item> 
    </string-array> 
</resources>