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

前端 未结 5 1514
既然无缘
既然无缘 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:06

    So I hate to answer my own question specifically with respect to the android.permission.WRITE_EXTERNAL_STORAGE permission used in my example, but what the heck.

    For reading and/or writing a file, there is actually a way to completely avoid having to ask for and then check for the permission and thus bypass the whole flow I described above. In this way, the saveFile (Url url, String content) method I gave as an example could continue to work synchronously.

    The solution, which I believe works in API 19+, eliminates the need for the WRITE_EXTERNAL_STORAGE permission by having a DocumentsProvider act as a "middleman" to basically ask the user on your app's behalf "please select the specific file to write to" (ie, a "file picker") and then once the user chooses a file (or types in a new file name), the app is now magically granted permission to do so for that Uri, since the user has specifically granted it.

    No "official" WRITE_EXTERNAL_STORAGE permission needed.

    This way of kind of borrowing permissions is part of the Storage Access Framework, and a discussion about this was made at the Big Android BBQ by Ian Lake. Here's a video called Forget the Storage Permission: Alternatives for sharing and collaborating that goes over the basics and how you specifically use it to bypass the WRITE_EXTERNAL_STORAGE permission requirement entirely.

    This doesn't completely solve the sync/async permissions problem for all cases, but for any type of external document, or even one that is offered by a provider (such as gDrive, Box.net, Dropbox, etc.) this may be a solution worth checking out.

提交回复
热议问题