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.
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.
“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.”
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With