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

前端 未结 5 1471
既然无缘
既然无缘 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 13:51

    You can Add a blocking helper method like this:

    @TargetApi(23) 
    public static void checkForPermissionsMAndAboveBlocking(Activity act) {
        Log.i(Prefs.TAG, "checkForPermissions() called");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Here, thisActivity is the current activity
            if (act.checkSelfPermission(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
    
    
                // No explanation needed, we can request the permission.
                act.requestPermissions(
                        new String[]{
                              Manifest.permission.WRITE_EXTERNAL_STORAGE
                        },
                        0);
    
                while (true) {
                    if (act.checkSelfPermission(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            == PackageManager.PERMISSION_GRANTED) {
    
                        Log.i(Prefs.TAG, "Got permissions, exiting block loop");
                        break;
                    }
                    Log.i(Prefs.TAG, "Sleeping, waiting for permissions");
                    try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
                }
    
            }
            // permission already granted
            else {
                Log.i(Prefs.TAG, "permission already granted");
            }
        }
        else {
            Log.i(Prefs.TAG, "Below M, permissions not via code");
        }
    
    }
    

提交回复
热议问题