How to read another app's data in Android 11 Flutter?

Viewed 499

I completed one of my apps and started testing. But I identified that my app doesn't work in Android 11. I want to get the file list of a folder of another app and to read the items in them. But it returns an empty list although there are files in that folder.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.status_saver">
   <uses-permission android:name="android.permission.INTERNET"/>
   <uses-permission 
android:name="android.permission.READ_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="28" />
   <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
   <application
        android:requestLegacyExternalStorage="true"
        android:label="status_saver"
        android:icon="@mipmap/ic_launcher">

This is how I read the files in the folder

var files = Directory(           "storage/emulated/0/Android/media/com.whatsapp/WhatsApp/Media/.Statuses")
        .listSync(recursive: true);
    print(files);

This is how I request permission.

void _grantPermission() async {
    var status = await Permission.storage.status;
    if (status.isGranted) {
      _getData();
    } else {
      await Permission.storage.request();
      status = await Permission.storage.status;
      _getData();
    }
    setState(() {
      mainStatus = status.isGranted;
    });
  }

This is happening because of Android 11's scoped storage as I think.

2 Answers

We need to request manage_external_storage permission via permission_handler.

Add this permission to AndroidManifest.xml

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

Request permission as shown below

await Permission.manageExternalStorage.request();

Then we can read any file and write to any location in Android 11.

After the change in Security policy for Android 9 or above. It is recommended to use the Storage Access Framework (SAF) API option to get access to storage (basic).

You can simply achieve that task using the flutter package called saf. You can search in the www.pub.dev package directory.

It basically gives you all the storage access framework API native implementation to the dart side. It opens the native OS file explorer then the user can grant permission of any particular directory and get access to perform some operations on it.

Related