cordova.file.externalRootDirectory not working in Android 11 devices

Viewed 1397

I not able to download file in android 11 version devices.

**Details :**

cordova android 10.1.0        
"cordova-plugin-file" version="6.0.2"           
"cordova-plugin-file-transfer" version="1.7.1"           
"cordova-plugin-filepath" version="1.6.0"   

**My Code:**

Below code I written to download files device its working in android 9 and 10 , when I target SDK 30 its not working and failing in only android 11.

window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, function(dir) {
    dir.getFile("test.pdf", {create:true}, function(file) {
        file.createWriter(function(fileWriter) {
        fileWriter.write("byteArrays data");
            alert('Message', 'File Downloaded Successfully');
        }, function(){
            alert('Error!', "Unable to save the file");
        });
    },function(e){
        alert('Error!', e);
    });
},function(e){
    console.log(e);
});

**I tried with below code in Androidmainfest file**

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



**Config.xml file**
<preference name="AndroidInsecureFileModeEnabled" value="true" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />

Please let me know if anything is missing , Thank you in advance.

2 Answers

I've found that the downloadFile method of the plugin Cordova Advanced HTTP is a great way to download files. I created this example app to show how it can work.

Note that the MANAGE_EXTERNAL_STORAGE permission has essentially been deprecated in Android 11 so you can no longer download to shared storage (e.g. cordova.file.externalRootDirectory which is shared by many apps -- a privacy and security risk). Try one of the directories scoped to your app such as cordova.file.externalDataDirectory.

On an Android 11+ device one cannot create files anymore in root of external storage (/storage/emulated/0).

Use an excisting public directory like DCIM, Pictures, Documents,.. there.

Related