Getting java.lang.SecurityException: Unsupported path. But I am asking for permissions

Viewed 5414

I am downloading files using DownloadManager to a directory, that isn't apart of my "local packages" directory, i.e. outside /storage/emulated/0/Android/data/myPackageName/, but part of another directory's package, more specifically, obb directory, /storage/emulated/0/Android/obb/otherPackageName/

If I install on "my package's directory", no problem, if I got outside of it, I get a "java.lang.SecurityException: Unsupported path /storage/emulated/0/Android/obb/otherPackageName/fileName.obb"

I have my permissions in the android manifest, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, and I check if I have them using ContextCompat.checkSelfPermission and see if it equals PackageManager.PERMISSION_GRANTED, which it does. But if it didn't, and for API level>=23, I use something along the lines of

requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, 
    Manifest.permission.READ_EXTERNAL_STORAGE}, CODE);

And then I use onRequestPermissionsResult() to check the response and see if it is a PackageManager.PERMISSION_GRANTED, so that I may be able to start the download.

Even with this, I am getting the exception. Can this be device specific or API specific? I'll have to test on other devices and API's to know for sure. Am I doing something wrong here? Do I need an extra permission? It has to be possible to write outside the directory?

Also, I am getting the external directory using Environment.getExternalStorageDirectory(), and then I add the subdirectories as a string (works for /storage/emulated/0/Android/data/myPackageName/..., but not for /storage/emulated/0/Android/obb/otherPackageName/...)

Thank you for reading, lemme know if you need any information.

2 Answers

I was directly storing the file outside my package's directory, and the exception was being thrown inside DownloadManager. So I started storing the file in the "local" directory, then manually moved it to the directory I wanted.

You can see this answer for an example method to move files: https://stackoverflow.com/a/11327789/13416944

Since I'm still using Environment.getExternalFilesDirectory(), and that's not really the best way to do it in these newer API's, I'll hopefully edit this answer once I find a better solution

I got this error in androids version above 10, But in lower Version everything is fine. For android above 10 i solve this problem by specifying subPath for Download manager and it seems necessary for version 10 and above:

 var request = DownloadManager.Request(uri)
 var filename = "MyApp" + imageId + "_.jpg"
 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,"your-sub-path")

Note that subpath is name of your downloaded file for example : landschaft.jpg

** Do not forget to add runtime Persmission:

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