Can you request permissions synchronously in Android Marshmallow (API 23)'s runtime permissions model?

前端 未结 5 1466
既然无缘
既然无缘 2021-02-01 13:09

Say you have a method like this:

public boolean saveFile (Url url, String content) {

   // save the file, this can be done a lot of different ways, but
   // ba         


        
5条回答
  •  一向
    一向 (楼主)
    2021-02-01 14:10

    As of Marshmallow, my understanding is that you can't.

    I had to solve the same issue in my app. Here's how I did it:

    1. Refactoring: Move every chunk of code that depends on permissions of some kind into a method of its own.
    2. More refactoring: Identify the trigger for each method (such as starting an activity, tapping a control etc.) and group methods together if they have the same trigger. (If two methods end up having the same trigger AND requiring the same set of permissions, consider merging them.)
    3. Even more refactoring: Find out what depends on the new methods having been called before, and make sure it is flexible about when these methods are called: Either move it into the method itself, or at least make sure that whatever you do doesn't throw exceptions if your method hasn't been called before, and that it starts behaving as expected as soon as the method is called.
    4. Request codes: For each of these methods (or groups thereof), define an integer constant to be used as a request code.
    5. Checking and asking for permissions: Wrap each of these methods/groups of methods into the following code:

    .

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.SOME_PERMISSION) == PackageManager.PERMISSION_GRANTED)
        doStuffThatRequiresPermission();
    else
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SOME_PERMISSION}, Const.PERM_REQUEST_DO_STUFF_THAT_REQUIRES_PERMISSION);
    
    1. Handling responses: Write an implementation for onRequestPermissionsResult() in every Activity that asks for permissions. Check if the requested permissions were granted, and use the request code to determine what method needs to be called.

    Be aware that the API requires an Activity for runtime permission requests. If you have non-interactive components (such as a Service), take a look at How to request permissions from a service in Android Marshmallow for advice on how to tackle this. Basically, the easiest way is to display a notification which will then bring up an Activity which does nothing but present the runtime permissions dialog. Here is how I tackled this in my app.

提交回复
热议问题