Question

With Google Play Services' Activity Recognition, they recommend that if the service disconnects (which it might) then we should remove the client:

http://developer.android.com/training/location/activity-recognition.html

In some cases, Location Services may disconnect from the activity recognition client before you call disconnect(). To handle this situation, implement onDisconnected(). In this method, set the request flag to indicate that a request is not in progress, and delete the client

That's fine, but it gives no instructions for how to reconnect [safely]. I'm running this from a foreground service which needs to maintain activity recognition at all times, so following disconnection:

@Override
    public void onDisconnected() {

        mRecognitionEnabled = false;
        mRequestInProgress = false;
        mRecognitionClient = null;

        //Re-initialise Activity Recognition if service is still running
        if (sServiceRunning) {          
            triggerActivityRecognition();
        }
    }

I reinstantiate the client and reconnect:

private void triggerActivityRecognition() {

    if (!mRequestInProgress ) {

        mRequestInProgress = true;          
        mRecognitionClient = new ActivityRecognitionClient(this, this, this);
        mRecognitionClient.connect();
    }    
}

But according to some of the bug reports I'm getting, there's an exception occurring as follows:

java.lang.NullPointerException
at com.google.android.gms.internal.bh.a(Unknown Source)
at com.google.android.gms.internal.k.f(Unknown Source)
at com.google.android.gms.internal.k$e.onServiceConnected(Unknown Source)
at com.google.android.gms.internal.l.a(Unknown Source)
at com.google.android.gms.internal.k.connect(Unknown Source)
at com.google.android.gms.location.ActivityRecognitionClient.connect(Unknown Source)
at com.myapp.MyService.triggerActivityRecognition(MyService.java:316)
at com.myapp.MyService.onDisconnected(MyService.java:407)
at com.google.android.gms.internal.k.A(Unknown Source)
at com.google.android.gms.internal.k$e.onServiceDisconnected(Unknown Source)
at com.google.android.gms.internal.l$a$a.onServiceDisconnected(Unknown Source)

The disconnection occurs rarely but results in the same stack trace every time.

So if this is being caused by Google Play Services, is there anything I can do to prevent it or is it a bug I need to log with Android?

Was it helpful?

Solution

This is what works for me:

Don't attempt the reconnect with the onDisconnect(), instead do nothing in the onDisconnect()

public void onDisconnected() {
 //do nothing here  
}

Simply use the client as before, but check if is connected

if (!mRecognitionClient.isConnected()) {
    // Client is disconnected, reconnect now
    mRecognitionClient.connect();
}

The PlayServices seems to reconnect very nicely.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top