简体   繁体   中英

Flutter Android 11 permissions like WhatsApp

I'm trying to build a Flutter application that runs on Android 11 and downloads files. I used to manage external storage permission to achieve this, but when the application asks for permission it goes to settings directly instead of asking for allow or deny within the app.

For example, WhatsApp stores data in the android/media folder, but it asks for permission directly within the application instead of going to the settings page. Please refer the below images:

My application goes to settings like this / I need something like this

My permission handling code

Future<bool> requestPermission() async {
  var androidInfo = await DeviceInfoPlugin().androidInfo;
  var release = int.parse(androidInfo.version.release);
  Permission permission;
  if (release < 11) {
    permission = Permission.storage;
  } else {
    permission = Permission.manageExternalStorage;
  }
  if (await permission.isGranted) {
    return true;
  } else {
    var result = await permission.request();
    if (result == PermissionStatus.granted) {
      return true;
    } else {
      return false;
    }
  }
}

These are two different approaches to manage the access the external storage in the Android device for Android 11 and above.

Files Go is trying to access the all files access permission . This gives app to access any read, write, access and share all files present in user storage(external or internal). You can read more about all files access permission from here - Manage all files on a storage device

WhatsApp - instead of asking for all files access permission , is saving its media in files directory. Saving in the files or cache directory doesn't need access to all flies and a simple permission dialog to write and read storage does the task.

You can read more about it in getExternalFilesDir .

Note: This only applies if your targetSdkVersion is 30. Targeting a 29 or below version, there isn't any need to all files permission as it's handled by the system.

You can refer to storage updates and request permission according to your use case in Storage updates in Android 11 .

Even if you are in Android 11 or above we have to ask the storage permission not the manage external storage permission in Flutter. I tried to write the files to 'android/media/packagename/' and it is working normally, but when I try to write into other locations it's not working. I think somehow Android internally is allowing to store data only in the same package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM