Search code examples
androidwear-osandroid-wear-data-api

GoogleApiClient onConnected not called on Watch


I have read this thread but I still faced similar issue:

GoogleApiClient onConnected never called on Wearable device

I tried to follow exactly how this works: https://developer.android.com/training/wearables/data-layer/events.html

Here are my codes:

public class Main extends Activity implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String PATH = "/phonewatch";
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d("phone watch", "On Create!");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    client = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
    ...
}

@Override
protected void onStart() {
    Log.d("phone watch", "On Start!");

    super.onStart();
    client.connect();
}

@Override
protected void onStop() {
    Log.d("phone watch", "On Stop!");

    if (client != null && client.isConnected()) {
        Wearable.DataApi.removeListener(client, this);
        client.disconnect();
    }

    super.onStop();
}

@Override
public void onConnected(Bundle bundle) {
    Log.d("phone watch", "On connected! Add listener.");

    Wearable.DataApi.addListener(client, this);
}

@Override
public void onConnectionSuspended(int i) {
    Log.d("phone watch", "connection suspended.");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.d("phone watch", "connection failed.");
}

@Override
public void onDataChanged(final DataEventBuffer dataEventBuffer) {
    Log.d("phone watch", "Data changed!");
...
}

I only got this:

07-23 20:07:41.730 24874-24874/virtualgs.phonewatch D/phone watch﹕ On Create! 07-23 20:07:41.772 24874-24874/virtualgs.phonewatch D/phone watch﹕ On Start!

On connected and other log messages were not called. Do I miss anything?


Solution

  • Although your activity implements GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener, you have never registered your activity as a listener to receive those callbacks. When building the api client, you need to call the following two: addConnectionCallbacks(this) and addOnConnectionFailedListener(this):

    client = new GoogleApiClient.Builder(this)
        .addApi(Wearable.API)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();