here is the code provided by the official guide, while this is a snippet causing problems.
@Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GooglePlayServicesUtil.getErrorDialog()
mResolvingError = true;
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, REQUEST_RESOLVE_ERROR)
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mResolvingError = false;
}
});
}
}
If I use it in a Service, when you read the variable this
passed as argument to those functions, they expect an Activity type.
How should I do? It's a Service.
For the same reason I can't get activity result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
This answer assumes your service is a "started" service. If it is a bound service or intent service, indicate that in a comment and I'll update the description and code included here.
The solution I suggest is to implement the activity shown below to handle the resolution UI. Replace the
onConnectionFailed()
method in your service with this code to hand off the resolution processing to theResolverActivity
:Add the activity shown below to your app. When the connection request in your service fails, the connection result, which is a
Parcelable
, is passed to the activity. The activity handles the resolution UI and when finished, returns the status to the service as an intent extra. You will need to modify the code in your service'sonStartCommand()
to examine the extras in the intent to determine if it is being called to start the service for the first time, or to receive resolution status from theResolverActivity
.An enhancement to this approach would be to post a notification with a
PendingIntent
forResolverActivity
instead of launching the activity immediately. That would give the user the option of deferring resolution of the connection failure.