Exception 'open failed: EACCES (Permission denied)' on Android
Asked Answered
L

38

417

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();
}
Lydon answered 13/1, 2012 at 17:3 Comment(2)
I had the same problem on an Android tablet, but my situation may be unique, so I report my solution here in a comment. The error occurred when the app tried to access directory /data/data/myapp/foo which had over 50 xml files. The app did not clean the folder due to a bug. After some old files were deleted, the error disappeared. I do not know why. It could be a problem of the generic Android device.Borrell
This solved me : #33666571Aesthetics
B
253

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.

Blunger answered 28/3, 2012 at 12:33 Comment(9)
it is that the uses-permission needs to be outside the applicationBlunger
I get a warning: "<uses-permission> tag appears after <application> tag"Upper
WARNING In android 4.4.4 do not use the parameter android:maxSdkVersion="18". It was generating this exceptionSalba
@Salba same job for me, but on Android 5.0.1. I was following the official tutorial which explicitly says to include android:maxSdkVersion="18" for android 4.4 onwards, but obviously that isn't trueVivianviviana
This permission is enforced starting in API level 19. Before API level 19, this permission is not enforced and all apps still have access to read from external storage.Taboret
i m using API lvl 15 , i m getting error while attempting to move file to OTG USB StickPostman
Very hard to find error unless you look at the log cat. It's a bit confusing if you 're using BitmapFactory.decodeFile() as is stays silent about any errorsTierell
I'm also facing the same problem and in my code, it is already placed there still getting the same error. The problem is with Android 10 when your app targeting API level 29.Forespeak
After API 29 you will need this: medium.com/@sriramaripirala/…Enarthrosis
Q
419

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.

Quorum answered 5/9, 2019 at 11:38 Comment(17)
@Billy i noticed it is only happens on devices with api 29. So i searched for changes in files providerQuorum
Finally got the cloudtestingscreenshotter_lib.aar to work with this line added to the androidTest manifest, thank you very much for this find.Robb
I would like to read more about this nice little black magic trick, but unfortunately the link returns a 404 error ... Thanks anywayPudens
its giving an warning android:requestLegacyExternalStorage="true" this wont break lower versions ryt ? @UrielFrankelHeadpiece
Link is still 404; is developer.android.com/training/data-storage#scoped-storage the updated url?Zoo
ocramot Fixed the linkQuorum
Man you saved me. I was trying everything to solve it. I was guessing the problem was Android 10 and you fixed it in just one line thank you (y)Cinchonize
you saved me sir this fixed the problem. But I have a question, I have two exact phones (PH-1) with exact versions (Android 10) but only one of them crache and the other doesn't crash. anyone have any idea why ?Zindman
Starting from Android 11 this is no longer validJargonize
@RoshanaPitigala what needs to be done for android 11 any link?Moritz
@SiddarthG developer.android.com/training/data-storage/use-casesQuorum
ridiculous things from the authority ! extra pain for developers, why ? is this our fault that we came to android ?Drink
I shouldn't search for this long to find this answerHygienic
Roshana Pitigala Android 11 you need permission : "android.permission.MANAGE_EXTERNAL_STORAGE"Ellis
@Mr. Lemon The Google Play store has a policy that limits usage of MANAGE_EXTERNAL_STORAGECounterreply
No. It's not working solution.Sassanid
This solution is not working for Android 13 devices.Hillhouse
G
370

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

Gybe answered 22/10, 2015 at 23:52 Comment(9)
Just to clarify, in order for this to work, the activity must handle the activity permissions request response. See developer.android.com/training/permissions/… for more details.Creator
Handy link with explanation and examples here inthecheesefactory.com/blog/…Lafave
isn't this a bad thing? with respect to user experience.Admonish
@usman wrt user experience, it is meant to be a good thing, since the user will be able to grant a single permission every time instead that all togheter, and the user would have a better understanding of what the application is doing on their phone. It will instead be a bad thing for user experience because the user will accept every permission request nevertheless, without even caring.Zoo
But where do I use it? for example, if I want to take a picture, do I have to run verifyStoragePermissions before startActivityForResult, or at onActivityResult? it really confuses me.Rabb
@Kiwi Lee you must use it before you decode your image. ie before using decodeFile(filepath) methodAmylose
Thanks this solve my problem. just a note: if someone can't resolve "Manifest.permission" you just need to import "import android.Manifest".Wester
You do not need to add READ_EXTERNAL_STORAGE, as WRITE_EXTERNAL_STORAGE counts as both. Source from official documentation developer.android.com/training/basics/data-storage/…Disbranch
@Creator this is not required now, just request permissionBewhiskered
B
253

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.

Blunger answered 28/3, 2012 at 12:33 Comment(9)
it is that the uses-permission needs to be outside the applicationBlunger
I get a warning: "<uses-permission> tag appears after <application> tag"Upper
WARNING In android 4.4.4 do not use the parameter android:maxSdkVersion="18". It was generating this exceptionSalba
@Salba same job for me, but on Android 5.0.1. I was following the official tutorial which explicitly says to include android:maxSdkVersion="18" for android 4.4 onwards, but obviously that isn't trueVivianviviana
This permission is enforced starting in API level 19. Before API level 19, this permission is not enforced and all apps still have access to read from external storage.Taboret
i m using API lvl 15 , i m getting error while attempting to move file to OTG USB StickPostman
Very hard to find error unless you look at the log cat. It's a bit confusing if you 're using BitmapFactory.decodeFile() as is stays silent about any errorsTierell
I'm also facing the same problem and in my code, it is already placed there still getting the same error. The problem is with Android 10 when your app targeting API level 29.Forespeak
After API 29 you will need this: medium.com/@sriramaripirala/…Enarthrosis
R
74

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">
Robertson answered 10/12, 2019 at 11:42 Comment(2)
not working in android 11Jaguarundi
@Jaguarundi You can refer developer.android.com/about/versions/11/privacy/storageRobertson
C
61

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.

Compotation answered 17/1, 2013 at 9:14 Comment(0)
H
53

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.

Headrace answered 19/11, 2012 at 8:42 Comment(1)
When I connect the Samsung Galaxy S6 device it first gives an option "Allow access to device data" with "DENY" or "ALLOW" and also from notification bar I am getting an option Use USB for 1. MTP 2. PTP 3. MIDI Devices 4. Charging. Which one to choose?Ebneter
M
34

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();
    }
}
Marlite answered 27/10, 2016 at 6:9 Comment(0)
K
34

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.

Kella answered 23/6, 2020 at 13:13 Comment(0)
M
27

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.

Misappropriate answered 21/10, 2019 at 15:5 Comment(2)
new error came out, ENOENT no file or dictionaryVerbify
I brought its name out in logs. And now its clear Environment.getExternalStorageDirectory(Environment.***) and context.getExternalFilesDir(Environment.***) are different paths . Thats all. Upvoting.Triiodomethane
F
20

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.

Fencer answered 8/2, 2018 at 6:26 Comment(1)
I'm unable to find this section?Technic
E
14

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.

Empoison answered 26/11, 2012 at 16:49 Comment(1)
I found the reason here #7397257 also see my answer https://mcmap.net/q/86103/-exception-39-open-failed-eacces-permission-denied-39-on-androidFireboard
M
13

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.

Moretta answered 14/10, 2015 at 13:42 Comment(0)
S
10

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.

Scowl answered 6/4, 2016 at 22:53 Comment(0)
H
9

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");
Hebbel answered 17/12, 2016 at 21:51 Comment(2)
Nothing strange here. With the first line you are trying to create a file in the same directory as the one that contains your external storage directory. ie /storage/.../somethingnewfile instead of /storage/.../something/newfileQianaqibla
The correct way to do this is to use the File(dir, file) cosntructorCourson
F
6

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.

Firewood answered 19/7, 2014 at 16:52 Comment(0)
H
6

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 !

Headpiece answered 1/4, 2020 at 12:38 Comment(1)
Thanks, however, this answer might not apply in the case where the said exception occurs as a result of trying to READ a file the user selected from file system - that is, the file already exists. And moreover, I already added the suggested parameters to the application's manifest.Hurless
V
5

I would expect everything below /data to belong to "internal storage". You should, however, be able to write to /sdcard.

Violante answered 13/1, 2012 at 17:9 Comment(2)
I tried <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" /> too. still same.Lydon
The /data-partition is generally write-protected to ordinary (non-root) users trying to to ordinary file access. For internal storage, there are specialized methods to do so, especially if you want to access databases. The Android developer pages should help you on this issue.Violante
O
5

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>
Odessa answered 4/12, 2013 at 15:47 Comment(1)
Fail. Put my device into a boot loop.Porcelain
E
5

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.

Elbow answered 21/8, 2016 at 12:43 Comment(0)
S
4

When your application belongs to the system application, it can't access the SD card.

Shulamith answered 21/11, 2012 at 7:41 Comment(0)
C
4

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

Cointreau answered 28/4, 2017 at 2:25 Comment(0)
M
4

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)

Micro answered 25/12, 2018 at 20:31 Comment(0)
B
4
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

Beadroll answered 19/7, 2019 at 11:58 Comment(0)
M
3

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
Mohenjodaro answered 28/8, 2017 at 19:51 Comment(0)
S
2

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!

Stickybeak answered 6/1, 2015 at 10:56 Comment(0)
F
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
Flinger answered 7/4, 2016 at 1:22 Comment(0)
C
2

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();
        }
    });
}
Capitalistic answered 29/11, 2021 at 7:47 Comment(0)
M
1

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)?

Milling answered 7/4, 2019 at 3:46 Comment(0)
Q
1

I Use the below process to handle the case with android 11 and targetapi30

  1. As pre-created file dir as per scoped storage in my case in root dir files//<Image/Video... as per requirement>

  2. Copy picked file and copy the file in cache directory at the time of picking from my external storage

  3. 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

Quadrant answered 23/9, 2021 at 11:24 Comment(0)
R
1

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
}
Replicate answered 3/6, 2022 at 12:17 Comment(0)
F
0

I had the same problem (API >= 23).

The solution https://mcmap.net/q/86103/-exception-39-open-failed-eacces-permission-denied-39-on-android worked for me, but it was not practical to disconnect app for debugging.

my solution was to install proper adb device driver on Windows. The google USB driver did not work for my device.

STEP 1: Download adb drivers for your device brand.

STEP 2: Go to device manager -> other devices -> look for entries with word "adb" -> select Update driver -> give location in step 1

Fireboard answered 9/5, 2017 at 7:19 Comment(0)
J
0

Add gradle dependencies

implementation 'com.karumi:dexter:4.2.0'

Add below code in your main activity.

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {


                checkMermission();
            }
        }, 4000);
    }

    private void checkMermission(){
        Dexter.withActivity(this)
                .withPermissions(
                        android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.ACCESS_NETWORK_STATE,
                        Manifest.permission.INTERNET
                ).withListener(new MultiplePermissionsListener() {
            @Override
            public void onPermissionsChecked(MultiplePermissionsReport report) {
                if (report.isAnyPermissionPermanentlyDenied()){
                    checkMermission();
                } else if (report.areAllPermissionsGranted()){
                    // copy some things
                } else {
                    checkMermission();
                }

            }
            @Override
            public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                token.continuePermissionRequest();
            }
        }).check();
    }
Jalopy answered 8/4, 2018 at 17:6 Comment(0)
C
0

Are you getting this crash while running the junit4 test of Jetpack Macrobenchmark in a real device?

If yes then increase the version of androidx.profileinstaller:profileinstaller.

Just click this link, find stable version and add to build.gradle(app).

For example implement(androidx.profileinstaller:profileinstaller:1.3.0).

I found it here: https://issuetracker.google.com/issues/203598149

Cucullate answered 13/4, 2023 at 8:53 Comment(0)
G
0

I also faced this problem and solved the problem with this method

   suspend fun copyFileToInternalStorage(context: Context,uri: Uri, newDirName: String): String? {
    val returnCursor = context.contentResolver.query(
        uri, arrayOf(
            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE
        ), null, null, null
    )


    /*
     * Get the column indexes of the data in the Cursor,
     *     * move to the first row in the Cursor, get the data,
     *     * and display it.
     * */
    val nameIndex = returnCursor!!.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    val sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE)
    returnCursor.moveToFirst()
    val name = returnCursor.getString(nameIndex)
    val output: File = if (newDirName != "") {
        val dir =
            File(context.filesDir.toString() + "/" + newDirName)
        if (!dir.exists()) {
            dir.mkdir()
        }
        File(context.filesDir.toString() + "/" + newDirName + "/" + name)
    } else {
        File(context.filesDir.toString() + "/" + name)
    }
    try {
        val inputStream =
            context.contentResolver.openInputStream(uri)
        val outputStream = FileOutputStream(output)
        var read = 0
        val bufferSize = 1024
        val buffers = ByteArray(bufferSize)
        while (inputStream!!.read(buffers).also { read = it } != -1) {
            outputStream.write(buffers, 0, read)
        }
        inputStream.close()
        outputStream.close()
    } catch (e: java.lang.Exception) {
        Log.e("Exception", e.message!!)
    }
    return output.path
}
Gnatcatcher answered 1/8, 2023 at 7:6 Comment(0)
N
0

If anyone is receiving this error using a hybrid app, using for example ionic, and the previous solutions did not work, first confirm that the path is valid.

If the error is coming from downloadFile or writeFile, confirm that there is not already a file in the location, it was my error.

The ionic standard library does not 'overwrite' and will throw an exception if the target file already exists, when trying to download or write. in this case the downloadFile itself tries to open and will throw EACCES exception

Solution:

If this is your problem you can save the file name with `_${Date.now()} at the end of the name or verify if the file exists and delete it before creating a new one.

issue

Nelle answered 4/12, 2023 at 13:22 Comment(0)
K
0

For API 33+ you need to request this permission to read Images

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

    String[] permissionNew = new String[]{ Manifest.permission.READ_MEDIA_IMAGES};
    String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};



private boolean checkPermissions() {
    int result;
    List<String> listPermissionsNeeded = new ArrayList<>();
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        for (String p : permissionsNew) {
            result = ContextCompat.checkSelfPermission(requireActivity(), p);
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p);
            }
        }
    } else {
        for (String p : permissions) {
            result = ContextCompat.checkSelfPermission(requireActivity(), p);
            if (result != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(p);
            }
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {
        requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 200);
        return false;
    }
    return true;
}
Knitted answered 26/12, 2023 at 9:51 Comment(0)
D
-1

Add Permission in manifest.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Diapositive answered 21/10, 2016 at 9:53 Comment(1)
There is no permission android.permission.READ_INTERNAL_STORAGESelfrighteous
U
-2

add this to manifest but this permission has a google play policy.

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Ulcer answered 12/7, 2022 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.