Skip to content

Instantly share code, notes, and snippets.

@adavis
Created July 28, 2014 14:46
Show Gist options
  • Save adavis/50fb525e4944550bb680 to your computer and use it in GitHub Desktop.
Save adavis/50fb525e4944550bb680 to your computer and use it in GitHub Desktop.
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