How to request permissions from a Service in Android Marshmallow

Tony Wickham picture Tony Wickham · Aug 30, 2015 · Viewed 60.6k times · Source

In Android Marshmallow, permissions should be requested at runtime when they are needed, instead of all at once when an app is installed. However, I can only seem to request permissions from an Activity, which is a problem since my app contains only Services. (Why is that, you might ask? The app has an Android Wear watch face bundled inside, and all the phone does is look up photos nearby to send to the watch - no Activity needed. But it does require location permissions.)

So, is there any way to request permissions from a Service? Or somehow force the permissions to be granted at install time as in the past?

Answer

Ali Naddaf picture Ali Naddaf · Aug 30, 2015

requestPermission() can only be called from an Activity and not a Service (unlike checkPermission() that only requires PackageManager). So you need to do some extra work to get around that; you do need to provide an Activity in your app and, for example, your Service can check for permissions it needs and if they have not been granted yet, it can create a notification and that can inform user with a descriptive short message as to why there is a notification and what needs to happen when they click on the notification, etc.