Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request Location Permissions from a service Android M

I am using a service that on boot starts up and begins to check for location updates. Once i deny location access on permission popup now thanks to Android M my service crashes once the phone boots up.

Since i have no activity in this case the call to requestPermissions() returns a ClassCastException as my service Context cannot be cast to an activity.

My method call:

ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_COARSE_LOCATION); 

Is there any solution so far to this OR do I have to revoke the service rights to NOT run in such a state.

like image 428
stud91 Avatar asked Nov 23 '15 09:11

stud91


People also ask

Can we request for permission from service Android?

You can check for permissions from anywhere (even from a service), based on whether the app is in foreground or background, it either shows normal dialog or generates a notification asking for permissions. The code is really easy to understand and it's really easy to use too.

What is Carrier Location Services permission request?

“The carrier is your phone service provider (eg. O2, Talktalk, Sky etc) location services allows the phone to determine where it is via the phone network. Some apps won't work without this being enabled.”


1 Answers

You can not request permission via a service, since a service is not tied to a UI, this kind of makes sense. Since a service context is not an activity the exception you are getting makes sense.

You can check if the permission is available in a service and request the permission in an activity (yes you need an activity).

In a service:

 public static boolean checkPermission(final Context context) { return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED         && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;  } 

and in an activity:

private void showPermissionDialog() {     if (!LocationController.checkPermission(this)) {         ActivityCompat.requestPermissions(             this,             new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},             PERMISSION_LOCATION_REQUEST_CODE);     } } 
like image 165
Joakim Engstrom Avatar answered Sep 25 '22 01:09

Joakim Engstrom