Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to determine if an Android Wear device is connected
private boolean isConnectedToWearable = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!servicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
isConnectedToWearable = false;
}
@Override
public void onConnected(Bundle dataBundle) {
if (servicesAvailable()) {
new CheckWearableConnected().execute();
}
}
private boolean servicesAvailable() {
// Check that Google Play Services are available
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
return (ConnectionResult.SUCCESS == resultCode);
}
private class CheckWearableConnected extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
NodeApi.GetConnectedNodesResult nodes =
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
if (nodes != null && nodes.getNodes().size() > 0) {
isConnectedToWearable = true;
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment