16

I'm trying to add GPS tracking functionality to my app by writing a GPS tracking Service. I've been following the Android Developer materials on how to do this via Google Play Services, but I'm stuck on the onConnectionFailed method. I'm trying to call startResolutionForResult to let Google Play Services handle the error. However this method requires that an activity be passed in as the first parameter, and since I'm calling it from a Service I'm not really sure what I should do.

I assume that I'm going about this all wrong and there's a completely different way to handle this from a service.

nybblesAndBits
  • 273
  • 2
  • 9

2 Answers2

2

The authentication process for Google Play Services needs an activity since it may need to display UI to the user. Since services don't have UI, you need to send a message to an activity to set up the connection, then the service can continue. There is a good answer demonstrating one way to do this here: Example: Communication between Activity and Service using Messaging

Community
  • 1
  • 1
Clayton Wilkinson
  • 4,524
  • 1
  • 16
  • 25
  • 1
    Such a strange solution. As it was announced on googleIO2015 user can disable some permissions. And how service should show UI dialog for user?! It's weird. – ruX Jun 02 '15 at 14:16
  • The new functionality in M will most likely change this behavior. Stay tuned! – Clayton Wilkinson Jun 02 '15 at 17:42
  • @ClaytonWilkinson How to do that properly? Should I just pass the `ConnectionResult` in a message to the activity and then in the activity call `startResolutionForResult`? Will that connect the API client used by the service, or should the service call `connect()` afterwards. Also, can I be sure this does not leak the Activity to the API connection used by the Service? – tron Dec 23 '15 at 19:33
2

You can use Status.getResolution() and start Activity with it. For example:

In Service

PendingIntent pI = status.getResolution();
mGoogleApiClient.getContext().startActivity(new Intent(mGoogleApiClient.getContext(), SomeActivity.class)
.putExtra("resolution", pI).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));

In Activity onCreate:

PendingIntent pI = (PendingIntent) (getIntent().getParcelableExtra("resolution"));
startIntentSenderForResult(pI.getIntentSender(),1,null,0,0,0);

also add onActivityResult(int requestCode, int resultCode, Intent data) to receive result of resolution

  • the resolution also can be obtained from the exception using (ResolvableApiException) e; – Chelo Aug 08 '18 at 23:43