I have an Android 7.0 test device and my APK targets = "targetSdkVersion 22", with:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
with:
final File f = new
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "DressUpBaby" + photonumber + ".png");
f.createNewFile();
and at this point I get the warning:
W/System.err: java.io.IOException: Permission denied
How to get it to save the file? This was working when I created this on Eclipse, but now that I have updated and moved to Android Studio it seems to have broken something.
On the Settings > Privacy > Permission manager > Files and media page, each app that has the permission is listed under Allowed for all files. If your app targets Android 11, keep in mind that this access to "all files" is read-only.
For solving this error, you need to add the correct permissions to the file to execute. However, you need to be a “root” user or have sudo access for changing the permission. For changing the permission, Linux offers a chmod command. The chmod stands for change mod.
Permission denied simply means the system is not having permission to write the file to that folder. Give permissions to the folder using "sudo chmod 777 " from terminal and try to run it.
UPDATE: See Volker Voecking's answer for a better solution
EDIT: This is simply a workaround for those who don't have time to look for a solution. *
If you get permission denied error even when the permissions are granted and you already implemented permission checks,
Change targetSdkVersion and compilesdkversion from 29 to 28 or any other lower level.
If you target SDK 29 and you still get a "permission denied" error after successfully requesting the WRITE_EXTERNAL_STORAGE permission you should add
android:requestLegacyExternalStorage="true"
to the application definition in AndroidManifest.xml.
<manifest ... >
<!-- This attribute is "false" by default on apps targeting
Android 10 or higher. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
see https://developer.android.com/training/data-storage/compatibility
If you're running your app on API level 23 or greater you have to request permission at runtime.
Request permission:
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, WRITE_REQUEST_CODE);
Then handle the result:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case WRITE_REQUEST_CODE:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Granted.
}
else{
//Denied.
}
break;
}
}
For more information visit Requesting Permissions at Run Time - Android Doc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With