Search code examples
androidservicepermissionslocationmanager

How to ask permissions from a Service


I am implementing a service that uses LocationManager to get and utilize the tablet location. This service is start and stop from an activity.

The latest Android requires that permissions are requested on runtime. Now I have managed to do this on an activity by using requestPermission in onCreate , checkSelfPermission everytime I use some Location manager function, and adding the requestPermission function and overriding the onRequestPermissionResult.

It works great.

Now for my service I need to do the same, but these functions seems to work only for activities. How can I activate permissions in a Service?


just in case, I have already asked for permissions in the activity that starts and stops the services


Solution

  • How can I activate permissions in a Service?

    You don't. You activate (i.e., request) permissions from an activity. That is not negotiable.

    Ideally, you request permissions before the activity starts the service or does something that will eventually cause the service to start (e.g., schedules the job with JobScheduler).

    If you determine that your service no longer has the necessary permissions — perhaps the user revoked them from Settings — you could raise a Notification that leads the user to an activity where you re-request the permissions.

    It is technically possible for a service to start an activity which requests the permissions. Usually, this is not a good idea, as you may not know what the user is doing at that moment, and the user may be unhappy to have you interrupt them with this permission request.