I am getting
open failed:
EACCES (Permission denied)
on the line OutputStream myOutput = new FileOutputStream(outFileName);
I checked the root, and I tried android.permission.WRITE_EXTERNAL_STORAGE.
How can I fix this problem?
try {
InputStream myInput;
myInput = getAssets().open("XXX.db");
// Path to the just created empty db
String outFileName = "/data/data/XX/databases/"
+ "XXX.db";
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
buffer = null;
outFileName = null;
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
asked Jan 13, 2012 at 17:03
2
Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:
<manifest ... >
<!-- This attribute is "false" by default on apps targeting Android Q. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
You can read more about it here: https://developer.android.com/training/data-storage/use-cases
Edit: I am starting to get downvotes because this answer is out of date for Android 11. So whoever sees this answer please go to the link above and read the instructions.
answered Sep 5, 2019 at 11:38
Uriel FrankelUriel Frankel
14.3k8 gold badges47 silver badges70 bronze badges
20
For API 23+ you need to request the read/write permissions even if they are already in your manifest.
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html
answered Oct 22, 2015 at 23:52
Justin FiedlerJustin Fiedler
6,4783 gold badges21 silver badges25 bronze badges
9
I had the same problem… The <uses-permission was in the wrong place. This is right:
<manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
<application>
...
<activity>
...
</activity>
</application>
</manifest>
The uses-permission tag needs to be outside the application tag.
answered Mar 28, 2012 at 12:33
user462990user462990
5,4723 gold badges33 silver badges35 bronze badges
10
Add android:requestLegacyExternalStorage=»true» to the Android Manifest
It’s worked with Android 10 (Q) at SDK 29+
or After migrating Android X.
<application
android:name=".MyApplication"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon=""
android:label=""
android:largeHeap="true"
android:supportsRtl=""
android:theme=""
android:requestLegacyExternalStorage="true">
answered Dec 10, 2019 at 11:42
rhaldarrhaldar
1,07510 silver badges6 bronze badges
3
I have observed this once when running the application inside the emulator. In the emulator settings, you need to specify the size of external storage («SD Card») properly. By default, the «external storage» field is empty, and that probably means there is no such device and EACCES is thrown even if permissions are granted in the manifest.
answered Jan 17, 2013 at 9:14
0
In addition to all the answers, make sure you’re not using your phone as a USB storage.
I was having the same problem on HTC Sensation on USB storage mode enabled. I can still debug/run the app, but I can’t save to external storage.
answered Nov 19, 2012 at 8:42
johnjohn
1,2821 gold badge17 silver badges30 bronze badges
2
My issue was with «TargetApi(23)» which is needed if your minSdkVersion is bellow 23.
So, I have request permission with the following snippet
protected boolean shouldAskPermissions() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
@TargetApi(23)
protected void askPermissions() {
String[] permissions = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"
};
int requestCode = 200;
requestPermissions(permissions, requestCode);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
if (shouldAskPermissions()) {
askPermissions();
}
}
answered Oct 27, 2016 at 6:09
PiroxiljinPiroxiljin
6216 silver badges14 bronze badges
0
Be aware that the solution:
<application ...
android:requestLegacyExternalStorage="true" ... >
Is temporary, sooner or later your app should be migrated to use Scoped Storage.
In Android 10, you can use the suggested solution to bypass the system restrictions, but in Android 11 (R) it is mandatory to use scoped storage, and your app might break if you kept using the old logic!
This video might be a good help.
answered Jun 23, 2020 at 13:13
omzeromzer
1,22012 silver badges14 bronze badges
0
Android 10 (API 29) introduces Scoped Storage. Changing your manifest to request legacy storage is not a long-term solution.
I fixed the issue when I replaced my previous instances of Environment.getExternalStorageDirectory() (which is deprecated with API 29) with context.getExternalFilesDir(null).
Note that context.getExternalFilesDir(type) can return null if the storage location isn’t available, so be sure to check that whenever you’re checking if you have external permissions.
Read more here.
answered Oct 21, 2019 at 15:05
jacoballenwoodjacoballenwood
2,7972 gold badges25 silver badges39 bronze badges
3
I’m experiencing the same. What I found is that if you go to Settings -> Application Manager -> Your App -> Permissions -> Enable Storage, it solves the issue.
answered Feb 8, 2018 at 6:26
Atul KaushikAtul Kaushik
5,1813 gold badges29 silver badges36 bronze badges
1
It turned out, it was a stupid mistake since I had my phone still connected to the desktop PC and didn’t realize this.
So I had to turn off the USB connection and everything worked fine.
answered Nov 26, 2012 at 16:49
Tobias ReichTobias Reich
4,9723 gold badges47 silver badges90 bronze badges
3
I had the same problem on Samsung Galaxy Note 3, running CM 12.1. The issue for me was that i had
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"/>
and had to use it to take and store user photos. When I tried to load those same photos in ImageLoader i got the (Permission denied) error. The solution was to explicitly add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
since the above permission only limits the write permission up to API version 18, and with it the read permission.
answered Oct 14, 2015 at 13:42
ZooSZooS
6588 silver badges18 bronze badges
1
In addition to all answers, if the clients are using Android 6.0, Android added new permission model for (Marshmallow).
Trick: If you are targeting version 22 or below, your application will request all permissions at install time just as it would on any device running an OS below Marshmallow. If you are trying on the emulator then from android 6.0 onwards you need to explicitly go the settings->apps-> YOURAPP -> permissions and change the permission if you have given any.
answered Apr 6, 2016 at 22:53
1
Strangely after putting a slash «/» before my newFile my problem was solved. I changed this:
File myFile= new File(Environment.getExternalStorageDirectory() + "newFile");
to this:
File myFile= new File(Environment.getExternalStorageDirectory() + "/newFile");
UPDATE:
as mentioned in the comments, the right way to do this is:
File myFile= new File(Environment.getExternalStorageDirectory(), "newFile");
answered Dec 17, 2016 at 21:51
DarushDarush
11.4k9 gold badges62 silver badges60 bronze badges
10
I had the same problem and none of suggestions helped. But I found an interesting reason for that, on a physical device, Galaxy Tab.
When USB storage is on, external storage read and write permissions don’t have any effect.
Just turn off USB storage, and with the correct permissions, you’ll have the problem solved.
answered Jul 19, 2014 at 16:52
1
To store a file in a directory which is foreign to the app’s directory is restricted above API 29+. So to generate a new file or to create a new file use your application directory like this :-
So the correct approach is :-
val file = File(appContext.applicationInfo.dataDir + File.separator + "anyRandomFileName/")
You can write any data into this generated file !
The above file is accessible and would not throw any exception because it resides in your own developed app’s directory.
The other option is android:requestLegacyExternalStorage="true" in manifest application tag as suggested by Uriel but its not a permanent solution !
answered Apr 1, 2020 at 12:38
Santanu SurSantanu Sur
11k7 gold badges33 silver badges52 bronze badges
1
I would expect everything below /data to belong to «internal storage». You should, however, be able to write to /sdcard.
answered Jan 13, 2012 at 17:09
ovenrorovenror
5524 silver badges11 bronze badges
2
Change a permission property in your /system/etc/permission/platform.xml
and group need to mentioned as like below.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<group android:gid="sdcard_rw" />
<group android:gid="media_rw" />
</uses-permission>
answered Dec 4, 2013 at 15:47
PrabakaranPrabakaran
1281 silver badge9 bronze badges
2
I had the same error when was trying to write an image in DCIM/camera folder on Galaxy S5 (android 6.0.1) and I figured out that only this folder is restricted. I simply could write into DCIM/any folder but not in camera.
This should be brand based restriction/customization.
answered Aug 21, 2016 at 12:43
When your application belongs to the system application, it can’t access the SD card.
answered Nov 21, 2012 at 7:41
0
Maybe the answer is this:
on the API >= 23 devices, if you install app (the app is not system app), you should check the storage permission in «Setting — applications», there is permission list for every app, you should check it on! try
answered Apr 28, 2017 at 2:25
Jason ZhuJason Zhu
711 silver badge6 bronze badges
keep in mind that even if you set all the correct permissions in the manifest:
The only place 3rd party apps are allowed to write on your external card are «their own directories»
(i.e. /sdcard/Android/data/)
trying to write to anywhere else: you will get exception:
EACCES (Permission denied)
answered Dec 25, 2018 at 20:31
EladElad
1,52313 silver badges10 bronze badges
Environment.getExternalStoragePublicDirectory();
When using this deprecated method from Android 29 onwards you will receive the same error:
java.io.FileNotFoundException: open failed: EACCES (Permission denied)
Resolution here:
getExternalStoragePublicDirectory deprecated in Android Q
answered Jul 19, 2019 at 11:58
user2965003user2965003
3262 silver badges11 bronze badges
0
In my case I was using a file picker library which returned the path to external storage but it started from /root/. And even with the WRITE_EXTERNAL_STORAGE permission granted at runtime I still got error EACCES (Permission denied).
So use Environment.getExternalStorageDirectory() to get the correct path to external storage.
Example:
Cannot write: /root/storage/emulated/0/newfile.txt
Can write: /storage/emulated/0/newfile.txt
boolean externalStorageWritable = isExternalStorageWritable();
File file = new File(filePath);
boolean canWrite = file.canWrite();
boolean isFile = file.isFile();
long usableSpace = file.getUsableSpace();
Log.d(TAG, "externalStorageWritable: " + externalStorageWritable);
Log.d(TAG, "filePath: " + filePath);
Log.d(TAG, "canWrite: " + canWrite);
Log.d(TAG, "isFile: " + isFile);
Log.d(TAG, "usableSpace: " + usableSpace);
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
Output 1:
externalStorageWritable: true
filePath: /root/storage/emulated/0/newfile.txt
isFile: false
usableSpace: 0
Output 2:
externalStorageWritable: true
filePath: /storage/emulated/0/newfile.txt
isFile: true
usableSpace: 1331007488
answered Aug 28, 2017 at 19:51
vovahostvovahost
34.3k17 gold badges114 silver badges118 bronze badges
1
I am creating a folder under /data/ in my init.rc (mucking around with the aosp on Nexus 7) and had exactly this problem.
It turned out that giving the folder rw (666) permission was not sufficient and it had to be rwx (777) then it all worked!
answered Jan 6, 2015 at 10:56
lanelane
63312 silver badges18 bronze badges
2
The post 6.0 enforcement of storage permissions can be bypassed if you have a rooted device via these adb commands:
root@msm8996:/ # getenforce
getenforce
Enforcing
root@msm8996:/ # setenforce 0
setenforce 0
root@msm8996:/ # getenforce
getenforce
Permissive
answered Apr 7, 2016 at 1:22
ZakirZakir
2,23221 silver badges31 bronze badges
i faced the same error on xiaomi devices (android 10 ). The following code fixed my problem.
Libraries: Dexter(https://github.com/Karumi/Dexter) and Image picker(https://github.com/Dhaval2404/ImagePicker)
Add manifest ( android:requestLegacyExternalStorage=»true»)
public void showPickImageSheet(AddImageModel model) {
BottomSheetHelper.showPickImageSheet(this, new BottomSheetHelper.PickImageDialogListener() {
@Override
public void onChooseFromGalleryClicked(Dialog dialog) {
selectedImagePickerPosition = model.getPosition();
Dexter.withContext(OrderReviewActivity.this) .withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
ImagePicker.with(OrderReviewActivity.this)
.galleryOnly()
.compress(512)
.maxResultSize(852,480)
.start();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
dialog.dismiss();
}
@Override
public void onTakePhotoClicked(Dialog dialog) {
selectedImagePickerPosition = model.getPosition();
ImagePicker.with(OrderReviewActivity.this)
.cameraOnly()
.compress(512)
.maxResultSize(852,480)
.start();
dialog.dismiss();
}
@Override
public void onCancelButtonClicked(Dialog dialog) {
dialog.dismiss();
}
});
}
answered Nov 29, 2021 at 7:47
Yasin EgeYasin Ege
6154 silver badges14 bronze badges
In my case the error was appearing on the line
target.createNewFile();
since I could not create a new file on the sd card,so I had to use the DocumentFile approach.
documentFile.createFile(mime, target.getName());
For the above question the problem may be solved with this approach,
fos=context.getContentResolver().openOutputStream(documentFile.getUri());
See this thread too,
How to use the new SD card access API presented for Android 5.0 (Lollipop)?
answered Apr 7, 2019 at 3:46
Sumit GaraiSumit Garai
1,2158 silver badges6 bronze badges
I Use the below process to handle the case with android 11 and targetapi30
-
As pre-created file dir as per scoped storage in my case in root dir files//<Image/Video… as per requirement>
-
Copy picked file and copy the file in cache directory at the time of picking from my external storage
-
Then at a time to upload ( on my send/upload button click) copy the file from cache dir to my scoped storage dir and then do my upload process
use this solution due to at time upload app in play store it generates warning for MANAGE_EXTERNAL_STORAGE permission and sometimes rejected from play store in my case.
Also as we used target API 30 so we can’t share or forward file from our internal storage to app
answered Sep 23, 2021 at 11:24
Arpan24x7Arpan24x7
6485 silver badges24 bronze badges
2022 Kotlin way to ask permission:
private val writeStoragePermissionResult =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->}
private fun askForStoragePermission(): Boolean =
if (hasPermissions(
requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
) {
true
} else {
writeStoragePermissionResult.launch(
arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
)
)
false
}
fun hasPermissions(context: Context, vararg permissions: String): Boolean = permissions.all {
ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
answered Jun 3, 2022 at 12:17
Guopeng LiGuopeng Li
811 silver badge9 bronze badges
Введение
Lucky Patcher — это популярное приложение для устройств на базе Android, которое позволяет пользователям вносить изменения в другие приложения, включая удаление рекламы, получение бесплатных покупок и многое другое. Однако, при попытке установить Lucky Patcher на устройствах MIUI, пользователи иногда сталкиваются с ошибкой «Install Failed internal error permission denied» (Ошибка установки, внутренняя ошибка, отказано в доступе). В данной статье рассматриваются частые причины этой ошибки и предлагаются решения для ее устранения.
Причины возникновения ошибки
Существует несколько причин, по которым может возникнуть ошибка «Install Failed internal error permission denied» при установке Lucky Patcher на телефоне MIUI. Вот некоторые из них:
-
Ограничения безопасности MIUI: MIUI имеет ряд встроенных ограничений безопасности, которые могут блокировать установку приложений, несоответствующих требованиям безопасности системы.
-
Блокировка установки из непроверенных источников: По умолчанию MIUI блокирует установку приложений из неизвестных источников, чтобы предотвратить установку вредоносных программ. Это может вызвать ошибку при попытке установить Lucky Patcher, так как оно не является официальным приложением из магазина приложений Google Play.
-
Конфликт с другими приложениями или системными параметрами: Иногда возникают конфликты с другими приложениями или системными параметрами, которые мешают правильной установке Lucky Patcher.
Советы по устранению проблемы
Вот несколько рекомендаций, которые могут помочь вам устранить ошибку «Install Failed internal error permission denied» на устройстве MIUI при установке Lucky Patcher:
-
Разрешить установку из неизвестных источников: Перейдите в настройки безопасности вашего устройства MIUI и разрешите установку приложений из неизвестных источников. Для этого найдите «Дополнительные настройки» -> «Безопасность» -> «Установка приложений из неизвестных источников» и установите переключатель в положение «Включено».
-
Временно отключите защиту MIUI: Если разрешение установки из неизвестных источников не помогло, вы можете временно отключить защиту MIUI. Для этого зайдите в настройки безопасности и найдите «Защита в реальном времени». Отключите эту функцию и повторите попытку установки Lucky Patcher.
-
Проверьте доступные обновления: Убедитесь, что ваша установка MIUI обновлена до последней версии. В некоторых случаях проблемы могут быть устранены путем установки последних обновлений операционной системы.
-
Удалите конфликтующие приложения: Если у вас установлены другие приложения, которые могут взаимодействовать с Lucky Patcher или вызывать конфликты, попробуйте их временно удалить. Затем повторите процесс установки Lucky Patcher.
-
Установите альтернативную версию Lucky Patcher: Если все вышеперечисленные решения не помогли, вы можете попробовать установить другую версию Lucky Patcher. Иногда более старые или альтернативные версии программы могут работать лучше на устройствах MIUI.
Заключение
Ошибка «Install Failed internal error permission denied» часто возникает при попытке установить Lucky Patcher на устройствах MIUI. Эта ошибка связана с ограничениями безопасности, блокировкой установки из неизвестных источников или конфликтами с другими приложениями. Следуя представленным выше советам, вы сможете устранить эту проблему и установить Lucky Patcher на ваше устройство MIUI.
I am getting
open failed:
EACCES (Permission denied)
on the line OutputStream myOutput = new FileOutputStream(outFileName);
I checked the root, and I tried android.permission.WRITE_EXTERNAL_STORAGE.
How can I fix this problem?
try {
InputStream myInput;
myInput = getAssets().open("XXX.db");
// Path to the just created empty db
String outFileName = "/data/data/XX/databases/"
+ "XXX.db";
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
buffer = null;
outFileName = null;
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
asked Jan 13, 2012 at 17:03
2
Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:
<manifest ... >
<!-- This attribute is "false" by default on apps targeting Android Q. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
You can read more about it here: https://developer.android.com/training/data-storage/use-cases
Edit: I am starting to get downvotes because this answer is out of date for Android 11. So whoever sees this answer please go to the link above and read the instructions.
answered Sep 5, 2019 at 11:38
Uriel FrankelUriel Frankel
14.3k8 gold badges47 silver badges70 bronze badges
20
For API 23+ you need to request the read/write permissions even if they are already in your manifest.
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For official documentation about requesting permissions for API 23+, check https://developer.android.com/training/permissions/requesting.html
answered Oct 22, 2015 at 23:52
Justin FiedlerJustin Fiedler
6,4783 gold badges21 silver badges25 bronze badges
9
I had the same problem… The <uses-permission was in the wrong place. This is right:
<manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
<application>
...
<activity>
...
</activity>
</application>
</manifest>
The uses-permission tag needs to be outside the application tag.
answered Mar 28, 2012 at 12:33
user462990user462990
5,4723 gold badges33 silver badges35 bronze badges
10
Add android:requestLegacyExternalStorage=»true» to the Android Manifest
It’s worked with Android 10 (Q) at SDK 29+
or After migrating Android X.
<application
android:name=".MyApplication"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon=""
android:label=""
android:largeHeap="true"
android:supportsRtl=""
android:theme=""
android:requestLegacyExternalStorage="true">
answered Dec 10, 2019 at 11:42
rhaldarrhaldar
1,07510 silver badges6 bronze badges
3
I have observed this once when running the application inside the emulator. In the emulator settings, you need to specify the size of external storage («SD Card») properly. By default, the «external storage» field is empty, and that probably means there is no such device and EACCES is thrown even if permissions are granted in the manifest.
answered Jan 17, 2013 at 9:14
0
In addition to all the answers, make sure you’re not using your phone as a USB storage.
I was having the same problem on HTC Sensation on USB storage mode enabled. I can still debug/run the app, but I can’t save to external storage.
answered Nov 19, 2012 at 8:42
johnjohn
1,2821 gold badge17 silver badges30 bronze badges
2
My issue was with «TargetApi(23)» which is needed if your minSdkVersion is bellow 23.
So, I have request permission with the following snippet
protected boolean shouldAskPermissions() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
@TargetApi(23)
protected void askPermissions() {
String[] permissions = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"
};
int requestCode = 200;
requestPermissions(permissions, requestCode);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
if (shouldAskPermissions()) {
askPermissions();
}
}
answered Oct 27, 2016 at 6:09
PiroxiljinPiroxiljin
6216 silver badges14 bronze badges
0
Be aware that the solution:
<application ...
android:requestLegacyExternalStorage="true" ... >
Is temporary, sooner or later your app should be migrated to use Scoped Storage.
In Android 10, you can use the suggested solution to bypass the system restrictions, but in Android 11 (R) it is mandatory to use scoped storage, and your app might break if you kept using the old logic!
This video might be a good help.
answered Jun 23, 2020 at 13:13
omzeromzer
1,22012 silver badges14 bronze badges
0
Android 10 (API 29) introduces Scoped Storage. Changing your manifest to request legacy storage is not a long-term solution.
I fixed the issue when I replaced my previous instances of Environment.getExternalStorageDirectory() (which is deprecated with API 29) with context.getExternalFilesDir(null).
Note that context.getExternalFilesDir(type) can return null if the storage location isn’t available, so be sure to check that whenever you’re checking if you have external permissions.
Read more here.
answered Oct 21, 2019 at 15:05
jacoballenwoodjacoballenwood
2,7972 gold badges25 silver badges39 bronze badges
3
I’m experiencing the same. What I found is that if you go to Settings -> Application Manager -> Your App -> Permissions -> Enable Storage, it solves the issue.
answered Feb 8, 2018 at 6:26
Atul KaushikAtul Kaushik
5,1813 gold badges29 silver badges36 bronze badges
1
It turned out, it was a stupid mistake since I had my phone still connected to the desktop PC and didn’t realize this.
So I had to turn off the USB connection and everything worked fine.
answered Nov 26, 2012 at 16:49
Tobias ReichTobias Reich
4,9723 gold badges47 silver badges90 bronze badges
3
I had the same problem on Samsung Galaxy Note 3, running CM 12.1. The issue for me was that i had
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"/>
and had to use it to take and store user photos. When I tried to load those same photos in ImageLoader i got the (Permission denied) error. The solution was to explicitly add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
since the above permission only limits the write permission up to API version 18, and with it the read permission.
answered Oct 14, 2015 at 13:42
ZooSZooS
6588 silver badges18 bronze badges
1
In addition to all answers, if the clients are using Android 6.0, Android added new permission model for (Marshmallow).
Trick: If you are targeting version 22 or below, your application will request all permissions at install time just as it would on any device running an OS below Marshmallow. If you are trying on the emulator then from android 6.0 onwards you need to explicitly go the settings->apps-> YOURAPP -> permissions and change the permission if you have given any.
answered Apr 6, 2016 at 22:53
1
Strangely after putting a slash «/» before my newFile my problem was solved. I changed this:
File myFile= new File(Environment.getExternalStorageDirectory() + "newFile");
to this:
File myFile= new File(Environment.getExternalStorageDirectory() + "/newFile");
UPDATE:
as mentioned in the comments, the right way to do this is:
File myFile= new File(Environment.getExternalStorageDirectory(), "newFile");
answered Dec 17, 2016 at 21:51
DarushDarush
11.4k9 gold badges62 silver badges60 bronze badges
10
I had the same problem and none of suggestions helped. But I found an interesting reason for that, on a physical device, Galaxy Tab.
When USB storage is on, external storage read and write permissions don’t have any effect.
Just turn off USB storage, and with the correct permissions, you’ll have the problem solved.
answered Jul 19, 2014 at 16:52
1
To store a file in a directory which is foreign to the app’s directory is restricted above API 29+. So to generate a new file or to create a new file use your application directory like this :-
So the correct approach is :-
val file = File(appContext.applicationInfo.dataDir + File.separator + "anyRandomFileName/")
You can write any data into this generated file !
The above file is accessible and would not throw any exception because it resides in your own developed app’s directory.
The other option is android:requestLegacyExternalStorage="true" in manifest application tag as suggested by Uriel but its not a permanent solution !
answered Apr 1, 2020 at 12:38
Santanu SurSantanu Sur
11k7 gold badges33 silver badges52 bronze badges
1
I would expect everything below /data to belong to «internal storage». You should, however, be able to write to /sdcard.
answered Jan 13, 2012 at 17:09
ovenrorovenror
5524 silver badges11 bronze badges
2
Change a permission property in your /system/etc/permission/platform.xml
and group need to mentioned as like below.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<group android:gid="sdcard_rw" />
<group android:gid="media_rw" />
</uses-permission>
answered Dec 4, 2013 at 15:47
PrabakaranPrabakaran
1281 silver badge9 bronze badges
2
I had the same error when was trying to write an image in DCIM/camera folder on Galaxy S5 (android 6.0.1) and I figured out that only this folder is restricted. I simply could write into DCIM/any folder but not in camera.
This should be brand based restriction/customization.
answered Aug 21, 2016 at 12:43
When your application belongs to the system application, it can’t access the SD card.
answered Nov 21, 2012 at 7:41
0
Maybe the answer is this:
on the API >= 23 devices, if you install app (the app is not system app), you should check the storage permission in «Setting — applications», there is permission list for every app, you should check it on! try
answered Apr 28, 2017 at 2:25
Jason ZhuJason Zhu
711 silver badge6 bronze badges
keep in mind that even if you set all the correct permissions in the manifest:
The only place 3rd party apps are allowed to write on your external card are «their own directories»
(i.e. /sdcard/Android/data/)
trying to write to anywhere else: you will get exception:
EACCES (Permission denied)
answered Dec 25, 2018 at 20:31
EladElad
1,52313 silver badges10 bronze badges
Environment.getExternalStoragePublicDirectory();
When using this deprecated method from Android 29 onwards you will receive the same error:
java.io.FileNotFoundException: open failed: EACCES (Permission denied)
Resolution here:
getExternalStoragePublicDirectory deprecated in Android Q
answered Jul 19, 2019 at 11:58
user2965003user2965003
3262 silver badges11 bronze badges
0
In my case I was using a file picker library which returned the path to external storage but it started from /root/. And even with the WRITE_EXTERNAL_STORAGE permission granted at runtime I still got error EACCES (Permission denied).
So use Environment.getExternalStorageDirectory() to get the correct path to external storage.
Example:
Cannot write: /root/storage/emulated/0/newfile.txt
Can write: /storage/emulated/0/newfile.txt
boolean externalStorageWritable = isExternalStorageWritable();
File file = new File(filePath);
boolean canWrite = file.canWrite();
boolean isFile = file.isFile();
long usableSpace = file.getUsableSpace();
Log.d(TAG, "externalStorageWritable: " + externalStorageWritable);
Log.d(TAG, "filePath: " + filePath);
Log.d(TAG, "canWrite: " + canWrite);
Log.d(TAG, "isFile: " + isFile);
Log.d(TAG, "usableSpace: " + usableSpace);
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
Output 1:
externalStorageWritable: true
filePath: /root/storage/emulated/0/newfile.txt
isFile: false
usableSpace: 0
Output 2:
externalStorageWritable: true
filePath: /storage/emulated/0/newfile.txt
isFile: true
usableSpace: 1331007488
answered Aug 28, 2017 at 19:51
vovahostvovahost
34.3k17 gold badges114 silver badges118 bronze badges
1
I am creating a folder under /data/ in my init.rc (mucking around with the aosp on Nexus 7) and had exactly this problem.
It turned out that giving the folder rw (666) permission was not sufficient and it had to be rwx (777) then it all worked!
answered Jan 6, 2015 at 10:56
lanelane
63312 silver badges18 bronze badges
2
The post 6.0 enforcement of storage permissions can be bypassed if you have a rooted device via these adb commands:
root@msm8996:/ # getenforce
getenforce
Enforcing
root@msm8996:/ # setenforce 0
setenforce 0
root@msm8996:/ # getenforce
getenforce
Permissive
answered Apr 7, 2016 at 1:22
ZakirZakir
2,23221 silver badges31 bronze badges
i faced the same error on xiaomi devices (android 10 ). The following code fixed my problem.
Libraries: Dexter(https://github.com/Karumi/Dexter) and Image picker(https://github.com/Dhaval2404/ImagePicker)
Add manifest ( android:requestLegacyExternalStorage=»true»)
public void showPickImageSheet(AddImageModel model) {
BottomSheetHelper.showPickImageSheet(this, new BottomSheetHelper.PickImageDialogListener() {
@Override
public void onChooseFromGalleryClicked(Dialog dialog) {
selectedImagePickerPosition = model.getPosition();
Dexter.withContext(OrderReviewActivity.this) .withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
if (report.areAllPermissionsGranted()) {
ImagePicker.with(OrderReviewActivity.this)
.galleryOnly()
.compress(512)
.maxResultSize(852,480)
.start();
}
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
dialog.dismiss();
}
@Override
public void onTakePhotoClicked(Dialog dialog) {
selectedImagePickerPosition = model.getPosition();
ImagePicker.with(OrderReviewActivity.this)
.cameraOnly()
.compress(512)
.maxResultSize(852,480)
.start();
dialog.dismiss();
}
@Override
public void onCancelButtonClicked(Dialog dialog) {
dialog.dismiss();
}
});
}
answered Nov 29, 2021 at 7:47
Yasin EgeYasin Ege
6154 silver badges14 bronze badges
In my case the error was appearing on the line
target.createNewFile();
since I could not create a new file on the sd card,so I had to use the DocumentFile approach.
documentFile.createFile(mime, target.getName());
For the above question the problem may be solved with this approach,
fos=context.getContentResolver().openOutputStream(documentFile.getUri());
See this thread too,
How to use the new SD card access API presented for Android 5.0 (Lollipop)?
answered Apr 7, 2019 at 3:46
Sumit GaraiSumit Garai
1,2158 silver badges6 bronze badges
I Use the below process to handle the case with android 11 and targetapi30
-
As pre-created file dir as per scoped storage in my case in root dir files//<Image/Video… as per requirement>
-
Copy picked file and copy the file in cache directory at the time of picking from my external storage
-
Then at a time to upload ( on my send/upload button click) copy the file from cache dir to my scoped storage dir and then do my upload process
use this solution due to at time upload app in play store it generates warning for MANAGE_EXTERNAL_STORAGE permission and sometimes rejected from play store in my case.
Also as we used target API 30 so we can’t share or forward file from our internal storage to app
answered Sep 23, 2021 at 11:24
Arpan24x7Arpan24x7
6485 silver badges24 bronze badges
2022 Kotlin way to ask permission:
private val writeStoragePermissionResult =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->}
private fun askForStoragePermission(): Boolean =
if (hasPermissions(
requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
) {
true
} else {
writeStoragePermissionResult.launch(
arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
)
)
false
}
fun hasPermissions(context: Context, vararg permissions: String): Boolean = permissions.all {
ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
answered Jun 3, 2022 at 12:17
Guopeng LiGuopeng Li
811 silver badge9 bronze badges
Today, I was working with my old program, which I had made in December 2020. Due to some odd reason, I delayed my app development process.
An application was working a few months ago when suddenly the app crashed with the error Exception ‘open failed: EACCES (Permission denied)’.
The application workflow was pretty simple. When the user clicks on the “Share Button” programmatically, the application will take a screenshot and use the explicit intent to send screenshots using any applications that support image share.
I took a paused for a moment and started thinking, What has suddenly happened to the project? If you read the error, it says something is wrong with the permissions.
Instantly, I checked the permissions code and found everything good. When I opened the Android manifest, I found the culprit: “WRITE_EXTERNAL_STORAGE no longer provides write access when targeting Android 10+.”

The problem starts getting clearer.
I open build.gradle and checked target version are changed to API 30 (Android 11) somehow.

As usual, I did research and found that the application target for SDK 29 or later uses scoped storage as the default option.
If you are thinking, What is Scoped Storage? I’ll clarify to you that Scoped Storage sets a limit on the access file.
For example, if my XYZ application is stored in a specific directory location, want to upload photos from any other directory other than the application directory, I’ll not be allowed to access the file according to the new Google policy.
So we’ve got the problem; tell me, Gagan, how to resolve this? You can use the MediaStore method or simply use the Legacy Storage policy.
How to resolve abov error using LegacyStorage?
We need to pass the single line of code, which will turn off the flag for Android 10+ devices, and you will be allowed to use LegacyStorage.
Go to the project pane, click on AndroidManifest, and add the highlighted code inside <application>.
<manifest ... >
<application
...
android:requestLegacyExternalStorage="true" ..>
...
</application>
</manifest>
Changes should be like this below sample image.

Once you add requestLegacyExternalStorage = “true” under the <application> tag. That’s all for Android 10 or 11 users. You can test your application.
For Android 12, users need to add one more tag in AndroidManifest.xml that is “android:exported=”true” for the MainActivity.

Run the application and your application functions will start working again.
Also Read: How to fix exposed beyond app through ClipData.Item.getUri
Wrap up
That’s it to resolve Exception ‘open failed: EACCES (Permission denied)’. If you are still facing any issues while following this guide, please let us know in the comment section.
For your ease, we have uploaded a sample project to the GitHub repository. To clone the repository click on this link.
What are your thoughts about this article?
A man with a tech effusive who has explored some of the amazing technology stuff and is exploring more. While moving towards, I had a chance to work on Android development, Linux, AWS, and DevOps with several open-source tools.
Эксклюзивные функции MIUI, такие как Second Space, позволяют с удовольствием настроить новый телефон с нуля. Существуют встроенные приложения для записи звонков, записи экрана и общесистемный темный режим, который был запущен с MIUI 10 (Android 9 Pie). Еще одна интересная функция — Dual Apps, которая позволяет дважды входить в одно и то же приложение с разными идентификаторами. Некоторые пользователи сталкивались с ошибкой отказа в разрешении для двух приложений.
Ошибка проявляется не тогда, когда пользователь пытается клонировать приложение, а когда он/она пытается его открыть. Нажатие на клонированное приложение ничего не дает, кроме как выводит эту ошибку на экран.
Давайте посмотрим, как это решить.
1. Выключите и снова включите
Может глюк какой-то. Вы пытались отключить эту функцию, а затем снова включить? Откройте «Настройки» и нажмите «Двойные приложения».
Нажмите на приложение, чтобы удалить клонированное приложение, и подождите несколько секунд. Когда вы увидите подтверждающее сообщение, снова включите его.
Нажмите на недавно клонированный значок, чтобы проверить, видите ли вы все еще ошибку «Отказано в разрешении для двух приложений».
Интересный факт:
2. Нажмите на исходную иконку
Вот простой трюк, который будет работать каждый раз. Когда вы ищете клонированное приложение, скажем, WhatsApp, вы видите два значка. Один оригинальный, который вы установили из Play Store, и один клонированный, с оранжевым значком в углу.
Нажмите на оригинальный значок, и MIUI спросит, какое приложение открыть — оригинальное или клонированное.
3. Откройте с помощью Google
Вы также можете использовать Google Assistant, чтобы открыть WhatsApp. Опять же, когда вы дадите команду «открыть WhatsApp» на своем телефоне, помощник попросит вас выбрать, какую версию WhatsApp вы хотите открыть.
Выберите тот, который вы хотите. Это может быть не простое решение, но оно работает нормально. Если вы используете голосовые команды, все станет проще.
4. Используйте второе пространство
Second Space — это не то же самое, что Dual Apps, но вы все равно можете использовать его для клонирования приложений. Вы создадите на своем телефоне отдельное пространство, в котором будут свои настройки и приложения. Войдите, используя другую учетную запись, и все готово.
Хотя это позволит вам установить одно и то же приложение дважды, вам придется переключаться между пробелами каждый раз, когда вы хотите использовать приложение. Это может быть немного громоздко, но у вас будет рабочее решение.
5. Сменить лаунчер
Я использую Nova Launcher, потому что это один из самых многофункциональных и гибких лаунчеров для экосистемы Android. Также известно, что он мешает работе двойных приложений. Грустный. Команда разработчиков работает над исправлением, а пока вам придется сменить лаунчер.
Мы рассмотрели несколько программ запуска на GT, таких как Action, Evie и Microsoft, которые я рекомендую вам проверить.
6. Разрешения приложения
Мы рассмотрим два разрешения приложения. Одним из них является приложение запуска, которое вы используете. Может быть, его настройка даст лучшие результаты? Стандартный лаунчер MIUI работает отлично, но довольно мягко. Nova launcher — это круто, но, как мы заметили ранее, он несовместим.
Откройте «Настройки», нажмите «Управление приложениями» и найдите свою программу запуска здесь.
Проверьте разрешения приложения, чтобы убедиться, что все, что нужно приложению для правильной работы, включено.
То же самое касается и других разрешений.
Вы повторите тот же процесс с разрешениями приложения, которое вы клонировали, и увидите ошибку отказа в разрешении. Найдите и откройте приложение и проверьте, есть ли у него все необходимые разрешения для правильной работы.
Parallel Space, одно из самых популярных приложений, позволит вам клонировать любое приложение на любой телефон Android, а не только на телефон MIUI. Установите приложение по ссылке ниже и запустите его.
Выберите приложение, которое хотите клонировать, и нажмите «Добавить в параллельное пространство». Вот и все. Одно заметное отличие заключается в том, что все ваши клонированные приложения будут находиться внутри Parallel Space, а не в панели приложений или на главном экране. Это означает несколько дополнительных нажатий, но не на что жаловаться.
Скачать параллельное пространство
Войны клонов
Dual Apps — это действительно классная функция, которая должна быть установлена на всех телефонах Android по умолчанию. К сожалению, это не так. Те, кто покупает телефоны с MIUI, сталкиваются с ошибкой отказа в разрешении. Однако есть способы решить эту ошибку или просто обойти ее. Все, что плывет в вашей лодке.
Следующий: Ищете другой лаунчер? Вот подробное сравнение между лаунчером MIUI и лаунчером Pixel.

















