Request Location Permissions from a service Android M

后端 未结 2 1008
轻奢々
轻奢々 2020-12-04 22:09

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 cras

相关标签:
2条回答
  • 2020-12-04 22:40

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-04 22:45

    You can check permissions without Activity by using application context, but you will need Activity when requesting permitions. To get app context just call to getApplicationContext() and to check permissions use ContextCompat.checkSelfPermission() instead.

    Also there is good information how to use runtime permissions in correct way:

    To check if you have a permission, call the ContextCompat.checkSelfPermission() method. For example, this snippet shows how to check if the activity has permission to write to the calendar:

    // Assume thisActivity is the current activity
    int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.WRITE_CALENDAR);
    

    If the app has the permission, the method returns PackageManager.PERMISSION_GRANTED, and the app can proceed with the operation. If the app does not have the permission, the method returns PERMISSION_DENIED, and the app has to explicitly ask the user for permission.

    Edit: After you check the permissions on service, you'll need the Activity to request permission:

    public static void requestPermissions (Activity activity, String[] permissions, int requestCode)
    
    0 讨论(0)
提交回复
热议问题