Ошибка permission denied android

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();
}

Randika Vishman's user avatar

asked Jan 13, 2012 at 17:03

Mert's user avatar

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 Frankel's user avatar

Uriel FrankelUriel Frankel

14.2k8 gold badges47 silver badges69 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

Raphael Royer-Rivard's user avatar

answered Oct 22, 2015 at 23:52

Justin Fiedler's user avatar

Justin FiedlerJustin Fiedler

6,4383 gold badges20 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.

Community's user avatar

answered Mar 28, 2012 at 12:33

user462990's user avatar

user462990user462990

5,4523 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

rhaldar's user avatar

rhaldarrhaldar

1,06510 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.

Peter Mortensen's user avatar

answered Jan 17, 2013 at 9:14

Audrius Meškauskas's user avatar

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.

Peter Mortensen's user avatar

answered Nov 19, 2012 at 8:42

john's user avatar

johnjohn

1,2821 gold badge17 silver badges30 bronze badges

2

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

omzer's user avatar

omzeromzer

1,09011 silver badges14 bronze badges

0

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

Piroxiljin's user avatar

PiroxiljinPiroxiljin

6016 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

jacoballenwood's user avatar

jacoballenwoodjacoballenwood

2,7572 gold badges23 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 Kaushik's user avatar

Atul KaushikAtul Kaushik

5,1713 gold badges28 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.

Peter Mortensen's user avatar

answered Nov 26, 2012 at 16:49

Tobias Reich's user avatar

Tobias ReichTobias Reich

4,9123 gold badges45 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

ZooS's user avatar

ZooSZooS

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

change_is_necessity's user avatar

answered Apr 6, 2016 at 22:53

Nourdine Alouane's user avatar

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

Darush's user avatar

DarushDarush

11.3k9 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.

Peter Mortensen's user avatar

answered Jul 19, 2014 at 16:52

Hamlet Kraskian's user avatar

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 Sur's user avatar

Santanu SurSantanu Sur

10.9k7 gold badges31 silver badges51 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

ovenror's user avatar

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>

AbdulMomen عبدالمؤمن's user avatar

answered Dec 4, 2013 at 15:47

Prabakaran's user avatar

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

Mahdi Mehrizi's user avatar

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

Peter Mortensen's user avatar

answered Nov 21, 2012 at 7:41

will's user avatar

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 Zhu's user avatar

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

Elad's user avatar

EladElad

1,52512 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

user2965003's user avatar

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

vovahost's user avatar

vovahostvovahost

33.7k16 gold badges111 silver badges113 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

lane's user avatar

lanelane

62312 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

Sergey Vyacheslavovich Brunov's user avatar

answered Apr 7, 2016 at 1:22

Zakir's user avatar

ZakirZakir

2,21220 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 Ege's user avatar

Yasin EgeYasin Ege

5853 silver badges13 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 Garai's user avatar

Sumit GaraiSumit Garai

1,1658 silver badges6 bronze badges

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

answered Sep 23, 2021 at 11:24

Arpan24x7's user avatar

Arpan24x7Arpan24x7

6485 silver badges23 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 Li's user avatar

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+.”

Exception 'open failed: EACCES (Permission denied) error message
AndroidManifest.xml

The problem starts getting clearer.

I open build.gradle and checked target version are changed to API 30 (Android 11) somehow.

build.gradle
build.gradle

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.

Exception 'open failed: EACCES (Permission denied)'
Add requestLegacyExternalStorage

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.

Exception 'open failed: EACCES (Permission denied)': Add exported tag
Add exported tag

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?

profile

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.

Cool! I’ve sent some coffee’s your way ☕️ .

In regards to the issue we’re having, we’ve changed the code to intermediately copy the file to a directory we have permissions with getApplicationDocumentsDirectory(), still seeing the same issues.

FileSystemException: FileSystemException: Cannot copy file to '/data/user/0/social.openbook.app/cache/mediaCache/fd3e9541-7ef2-40b9-85af-18373f02e208VID_20191102_164450.mp4', path = '/storage/emulated/0/DCIM/Camera/VID_20191102_164450.mp4' (OS Error: Permission denied, errno = 13)
  File "create_post.dart", line 609, in OBSavePostModalState._onError
  File "async_patch.dart", line 43, in _AsyncAwaitCompleter.start
  File "create_post.dart", line 593, in OBSavePostModalState._onError
  File "create_post.dart", line 410, in OBSavePostModalState._getImagePostActions.<fn>
  File "async_patch.dart", line 78, in _asyncErrorWrapperHelper.<fn>
  File "zone.dart", line 1144, in _rootRunBinary
  File "zone.dart", line 1037, in _CustomZone.runBinary
  File "future_impl.dart", line 151, in _FutureListener.handleError
  File "future_impl.dart", line 690, in Future._propagateToListeners.handleError
  File "future_impl.dart", line 711, in Future._propagateToListeners
  File "future_impl.dart", line 530, in Future._completeError
  File "async_patch.dart", line 36, in _AsyncAwaitCompleter.completeError
  File "media.dart", line 0, in MediaService.pickVideo
  File "async_patch.dart", line 71, in _asyncThenWrapperHelper.<fn>
  File "zone.dart", line 1132, in _rootRunUnary
  File "zone.dart", line 1029, in _CustomZone.runUnary
  File "future_impl.dart", line 137, in _FutureListener.handleValue
  File "future_impl.dart", line 678, in Future._propagateToListeners.handleValueCallback
  File "future_impl.dart", line 707, in Future._propagateToListeners
  File "future_impl.dart", line 522, in Future._completeWithValue
  File "async_patch.dart", line 30, in _AsyncAwaitCompleter.complete
  File "async_patch.dart", line 288, in _completeOnAsyncReturn
  File "media.dart", line 0, in MediaService._getTempPath
  File "async_patch.dart", line 71, in _asyncThenWrapperHelper.<fn>
  File "zone.dart", line 1132, in _rootRunUnary
  File "zone.dart", line 1029, in _CustomZone.runUnary
  File "future_impl.dart", line 137, in _FutureListener.handleValue
  File "future_impl.dart", line 678, in Future._propagateToListeners.handleValueCallback
  File "future_impl.dart", line 707, in Future._propagateToListeners
  File "future_impl.dart", line 522, in Future._completeWithValue
  File "future_impl.dart", line 552, in Future._asyncComplete.<fn>
  File "zone.dart", line 1124, in _rootRun
  File "zone.dart", line 1021, in _CustomZone.run
  File "zone.dart", line 923, in _CustomZone.runGuarded
  File "zone.dart", line 963, in _CustomZone.bindCallbackGuarded.<fn>
  File "schedule_microtask.dart", line 41, in _microtaskLoop
  File "schedule_microtask.dart", line 50, in _startMicrotaskLoop

With the code

    final tempPath = await _getTempPath();

    final String processedImageUuid = _uuid.v4();
    String imageExtension = basename(pickedImage.path);

    // The image picker gives us the real image, lets copy it into a temp path
    pickedImage =
        pickedImage.copySync('$tempPath/$processedImageUuid$imageExtension');

I’ve found this issue on the image picker package which might be related
flutter/flutter#41459

People suggest removing some legacy flag as seen here flutter/flutter#41459 (comment) or downgrading to target sdk 28 instead of the latest 29 as a workaround.

If it’s really a bug, perhaps an interesting thread to follow for the fix on this library too.

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();
}

Randika Vishman's user avatar

asked Jan 13, 2012 at 17:03

Mert's user avatar

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 Frankel's user avatar

Uriel FrankelUriel Frankel

14k8 gold badges45 silver badges67 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

Raphael Royer-Rivard's user avatar

answered Oct 22, 2015 at 23:52

Justin Fiedler's user avatar

Justin FiedlerJustin Fiedler

6,3723 gold badges20 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.

Community's user avatar

answered Mar 28, 2012 at 12:33

user462990's user avatar

user462990user462990

5,4443 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

rhaldar's user avatar

rhaldarrhaldar

1,06510 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.

Peter Mortensen's user avatar

answered Jan 17, 2013 at 9:14

Audrius Meškauskas's user avatar

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.

Peter Mortensen's user avatar

answered Nov 19, 2012 at 8:42

john's user avatar

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

Piroxiljin's user avatar

PiroxiljinPiroxiljin

5915 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

omzer's user avatar

omzeromzer

90010 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

jacoballenwood's user avatar

jacoballenwoodjacoballenwood

2,6722 gold badges22 silver badges38 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 Kaushik's user avatar

Atul KaushikAtul Kaushik

5,1533 gold badges28 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.

Peter Mortensen's user avatar

answered Nov 26, 2012 at 16:49

Tobias Reich's user avatar

Tobias ReichTobias Reich

4,8143 gold badges46 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

ZooS's user avatar

ZooSZooS

6388 silver badges15 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.

change_is_necessity's user avatar

answered Apr 6, 2016 at 22:53

Nourdine Alouane's user avatar

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

Darush's user avatar

DarushDarush

11k9 gold badges61 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.

Peter Mortensen's user avatar

answered Jul 19, 2014 at 16:52

Hamlet Kraskian's user avatar

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

ovenror's user avatar

ovenrorovenror

5324 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>

AbdulMomen عبدالمؤمن's user avatar

answered Dec 4, 2013 at 15:47

Prabakaran's user avatar

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

Mahdi Mehrizi's user avatar

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 Zhu's user avatar

Jason ZhuJason Zhu

731 silver badge6 bronze badges

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 Sur's user avatar

Santanu SurSantanu Sur

10.6k7 gold badges31 silver badges50 bronze badges

1

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

Peter Mortensen's user avatar

answered Nov 21, 2012 at 7:41

will's user avatar

0

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

Elad's user avatar

EladElad

1,44712 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

user2965003's user avatar

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

vovahost's user avatar

vovahostvovahost

32.5k15 gold badges110 silver badges109 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

lane's user avatar

lanelane

62315 silver badges18 bronze badges

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

Sergey Vyacheslavovich Brunov's user avatar

answered Apr 7, 2016 at 1:22

Zakir's user avatar

ZakirZakir

2,19219 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 Ege's user avatar

Yasin EgeYasin Ege

4633 silver badges10 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

Tarasantan's user avatar

TarasantanTarasantan

1,0458 silver badges6 bronze badges

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

answered Sep 23, 2021 at 11:24

Arpan24x7's user avatar

Arpan24x7Arpan24x7

6485 silver badges23 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 Li's user avatar

Guopeng LiGuopeng Li

711 silver badge9 bronze badges

Содержание

  1. Android permission doesn’t work even if I have declared it
  2. 11 Answers 11
  3. Android can’t open file, FileNotFoundException(Permission denied), but PermissionRead is granted [duplicate]
  4. 3 Answers 3
  5. Conclusion: Solution
  6. Why: Reasons to fix
  7. Android: adb: Permission Denied
  8. 10 Answers 10
  9. update 2022
  10. Android Studio error 13=permission denied in linux
  11. 14 Answers 14
  12. SecurityException: Permission denied (missing INTERNET permission?)
  13. 13 Answers 13

Android permission doesn’t work even if I have declared it

I’m trying to write code to send an SMS from an Android app, but when I try to send the SMS it sends me back the error:

I checked but I have the permissions in the manifest, as follows:

I searched the internet but all the errors were about the syntax, could you help me please?

11 Answers 11

The big reason for not getting your permission nowadays is because your project has a targetSdkVersion of 23 or higher, and the permission that you are requesting is «dangerous». In Android 6.0, this includes:

  • ACCEPT_HANDOVER
  • ACCESS_BACKGROUND_LOCATION
  • ACCESS_MEDIA_LOCATION
  • ACTIVITY_RECOGNITION
  • ANSWER_PHONE_CALLS
  • ACCESS_COARSE_LOCATION
  • ACCESS_FINE_LOCATION
  • ADD_VOICEMAIL
  • BODY_SENSORS
  • CALL_PHONE
  • CAMERA
  • GET_ACCOUNTS
  • PROCESS_OUTGOING_CALLS
  • READ_CALENDAR
  • READ_CALL_LOG
  • READ_CELL_BROADCASTS
  • READ_CONTACTS
  • READ_EXTERNAL_STORAGE
  • READ_PHONE_STATE
  • READ_SMS
  • RECEIVE_MMS
  • RECEIVE_SMS
  • RECEIVE_WAP_PUSH
  • RECORD_AUDIO
  • SEND_SMS
  • USE_SIP
  • WRITE_CALENDAR
  • WRITE_CALL_LOG
  • WRITE_CONTACTS
  • WRITE_EXTERNAL_STORAGE

For these permissions, not only does your targetSdkVersion 23+ app need to have the element(s), but you also have to ask for those permissions at runtime from the user on Android 6.0+ devices, using methods like checkSelfPermission() and requestPermissions() .

As a temporary workaround, drop your targetSdkVersion below 23.

However, eventually, you will have some reason to want your targetSdkVersion to be 23 or higher. At that time, you will need to adjust your app to use the new runtime permission system. The Android documentation has a page dedicated to this topic.

Источник

Android can’t open file, FileNotFoundException(Permission denied), but PermissionRead is granted [duplicate]

Android can’t open file with FileNotFoundException(Permission denied), but PermissionRead is granted.

java.io.FileNotFoundException: /mnt/obb/»file detailed path»: open failed: EACCES (Permission denied)

obb file is ERROR_ALREADY_MOUNTED.

PermissionRead is granted.

Android OS ver.6.0 device.

3 Answers 3

Try to give runtime permission

have you implemented runtime permission?, first you grant manually storage permission from settings and check exception occur or not, if not then you have mistake in permission implementation.

Thank you for answers.

This is a very strange phenomenon. Once, I was able to fix it to work properly.

Conclusion: Solution

Create an obb file with jobb command with the same name as renamed on Google Play side.

That is. Before the fix was done like this.(example)

And if you upload «main1.obb» to Google Play, «main.1.com.test.testapp.obb» will be downloaded along with apk download.

But this is not good.

After the correction, it was programmed like this.

Why: Reasons to fix

I thought that there was a problem with obb mount when the following error occurred:

So I tried to unmount obb after the error. Then an error came back.

If I try to unmount an already mounted obb, it is a permission error. This is strange.

As I looked it up on the Internet, the problem is obb filename made with the jobb command? Or package name? It was said that it occurred.

Therefore, I changed the obb file name generated by the jobb command. There is no problem with this. Of course, «READ_EXTERNAL_STORAGE» has always acquired.

I did not understand anything more. Just the application is working correctly.

Источник

Whatever I type after adb shell it fails with Permission denied :

10 Answers 10

According to adb help :

Which indeed resolved the issue for me.

Without rooting: If you can’t root your phone, use the run-as

command to be able to access data of your application.

$ adb exec-out run-as com.yourcompany.app ls -R /data/data/com.yourcompany.app/

exec-out executes the command without starting a shell and mangling the output.

The reason for «permission denied» is because your Android machine has not been correctly rooted. Did you see $ after you started adb shell ? If you correctly rooted your machine, you would have seen # instead.

If you see the $ , try entering Super User mode by typing su . If Root is enabled, you will see the # — without asking for password.

You might need to activate adb root from the developer settings menu. If you run adb root from the cmd line you can get:

Once you activate the root option (ADB only or Apps and ADB) adb will restart and you will be able to use root from the cmd line.

None of the previous solutions worked for me but I was able to make it work using this command

The data partition is not accessible for non-root users, if you want to access it you must root your phone.

ADB root does not work for all product and depend on phone build type.

in the new version of android studio, you can explore /data/data path for debuggable apps.

update 2022

Android Studio new versions have some tools like Device Explorer and App Inspection to access application data. (app must be debuggable).

Источник

Android Studio error 13=permission denied in linux

i am using android studio latest version in linux(elementary luna to be specific). I installed jdk, android studio and sdk successfully, android studio opens us perfectly and even i can work on my app. but when i bulid app it gives error 13: permission denied and it opens a black circle image png in new tab.

i dont understand the problem. i did searched on internet and tried many methods like

changing permissions with chmod:

chmod +x /home/alex/android-studio/sdk/build-tools/android-4.2.2/dx

it executes successfully but with no effect on the problem itself,

2.closing and re-importing project,

3.i also tried this,

and i get following result

i guess this is not issue since my system is 32 bit and this is for 64 bit systems.

Can anyone help? since i am really counting on it.

my system configurations:(if useful)

-OS Version: 0.2.1 «Luna» ( 32-bit ), Built on: Ubuntu 12.04 ( «Precise» )

-installed OpenJdk 7: java version «1.6.0_34» OpenJDK Runtime Environment (IcedTea6 1.13.6) (6b34-1.13.6-1ubuntu0.12.04.1)

OpenJDK Client VM (build 23.25-b01, mixed mode, sharing)

14 Answers 14

I’m running android studio 1.0.2 on ubuntu 14.04 (LTS) 32 bit and i had the same problem. just go to «/home/suUs12/Android/Sdk/build-tools/21.1.2/» and then right click on ‘aapt‘ file , properties -> permissions and check ‘Allow executing file as program‘. then close the window.

In my case,after giving permission for ‘aapt‘ file, I had to give the same permission for ‘dx‘ and ‘zipalign‘ files in the same directory (/home/suUs12/Android/Sdk/build-tools/21.1.2/) and I was able to run my first app using android studio.

Give Root permission to your android studio by using

chmod -777 YourAndroidStudioFolder

This problem is about insufficient authority. If you change your user as ‘root’ and you open android studio, this problem will be resolved. For ex;

[enter your password] : ********

$ cd /home/username/. /android-studio/bin

If this can help, I solved after giving full execution permissions ( chmod a+x ) to all executables in /opt/android-bundle/sdk/build-tools/$VERSION/ ( aapt , dx and zipalign ).

The permissions problem with file not found with aapt wasn’t with this file itself but with the *.so files it tries to use. The first thing to do which I didn’t at first was run the following sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686 to get the necessary 32 bit *.so files installed. I found out about the missing *.so files by running aapt outside the studio. I also found there were a number of files that were read or read write only that needed to be executable in these directories. android-studio/bin android-studio/jre/bin android-studio/jre/jre/bin android-studio/gradle/gradle-2.14.1/bin

The fsnotifier files and the 2 *.sh file in the first bin directory. All the files in the two jre directories and the gradle file in the last directory needed to be chmod 755. After I did that I no longer get the pop up box about the fsnotifier and the gradle build doesn’t get the permission error. Running as root doesn’t help when the problem is with files not being executable.

I Solved This Problem By : Right Click On Main Folder Like Android-Studio and then Go to Properties and then Click On Permission and check CheckBox For Allow Executing File As a Program Then Run Android Studio In Terminal 🙂

Remove the build tool and re download it fixes my problem.

just reinstall the build tool version and then go into folder where sdk is installed and in build tool version’s «aapt» file and change permissions from «property» all to read and write and check mark to «Allow executing file as a program» and then close it. same problem is solved by doing this.

You can reinstall androidstudio in /opt/ folder.This is a shared folder.I refer to official web’s vedio on how to install androidstudio and solve the problem.I almost tried every way on the internet,but it didn’t work.In fact,this is just a question about permission.

In my case the partition in which I saved the Sdk was mounted with the defaults option in /etc/fstab, which in turn enabled the default noexec option which forbids execution for all files in that partition.

Then I edited that line in fstab appending exec, resulting in the options list ‘user,defaults,exec’ for that partition.

Источник

SecurityException: Permission denied (missing INTERNET permission?)

this error is really really really strange and I don’t know how to reproduce it and how to fix it because I made a lot of searches but nothing was useful.

Here’s the stacktrace:

Here’s my AndroidManifest.xml

Please don’t bother asking me if I have the correct INTERNET permission in my manifest because this app is in market since 2 years 😛

I’ve also noticed that (from Crittercism) all bugs are coming from Android 4.1.x version (JB). I don’t know if device are rooted or what (I can’t see this information for the moment)

13 Answers 13

NOTE: I wrote this answer in Jun 2013, so it’s bit dated nowadays. Many things changed in Android platform since version 6 (Marshmallow, released late 2015), making the whole problem more/less obsolete. However I believe this post can still be worth reading as general problem analysis approach example.

Exception you are getting ( SecurityException: Permission denied (missing INTERNET permission?) ), clearly indicates that you are not allowed to do networking. That’s pretty indisputable fact. But how can this happen? Usually it’s either due to missing entry in your AndroidManifest.xml file or, as internet permission is granted at installation not at run time, by long standing, missed bug in Android framework that causes your app to be successfully installed, but without expected permission grant.

My Manifest is correct, so how can this happen?

Theoretically, presence of uses-permission in Manifest perfectly fulfills the requirement and from developer standpoint is all that’s needed to be done to be able to do networking. Moreover, since permissions are shown to the user during installation, the fact your app ended installed on user’s device means s/he granted what you asked for (otherwise installation is cancelled), so assumption that if your code is executed then all requested permissions are granted is valid. And once granted, user cannot revoke the permission other way than uninstalling the app completely as standard Android framework (from AOSP) offers no such feature at the moment.

But things are getting more tricky if you also do not mind your app running on rooted devices too. There’re tools available in Google Play your users can install to control permission granted to installed apps at run-time — for example: Permissions Denied and others. This can also be done with CyanogenMod, vendor brand (i.e. LG’s) or other custom ROM, featuring various type of «privacy managers» or similar tools.

So if app is blocked either way, it’s basically blocked intentionally by the user and if so, it is really more user problem in this case (or s/he do not understand what certain options/tools really do and what would be the consequences) than yours, because standard SDK (and most apps are written with that SDK in mind) simply does not behave that way. So I strongly doubt this problem occurs on «standard», non-rooted device with stock (or vendor like Samsung, HTC, Sony etc) ROM.

I do not want to crash.

Properly implemented permission management and/org blocking must deal with the fact that most apps may not be ready for the situation where access to certain features is both granted and not accessible at the same time, as this is kind of contradiction where app uses manifest to request access at install time. Access control done right should must make all things work as before, and still limit usability using techniques in scope of expected behavior of the feature. For example, when certain permission is granted (i.e. GPS, Internet access) such feature can be made available from the app/user perspective (i.e. you can turn GPS on. or try to connect), the altered implementation can provide no real data — i.e. GPS can always return no coordinates, like when you are indoor or have no satellite «fix». Internet access can be granted as before, but you can make no successful connection as there’s no data coverage or routing. Such scenarios should be expected in normal usage as well, therefore it should be handled by the apps already. As this simply can happen during normal every day usage, any crash in such situation should be most likely be related to application bugs.

We lack too much information about the environment on which this problem occurs to diagnose problem w/o guessing, but as kind of solution, you may consider using setDefaultUncaughtExceptionHandler() to catch such unexpected exceptions in future and i.e. simply show user detailed information what permission your app needs instead of just crashing. Please note that using this will most likely conflict with tools like Crittercism, ACRA and others, so be careful if you use any of these.

Notes

Please be aware that android.permission.INTERNET is not the only networking related permission you may need to declare in manifest in attempt to successfully do networking. Having INTERNET permission granted simply allows applications to open network sockets (which is basically fundamental requirement to do any network data transfer). But in case your network stack/library would like to get information about networks as well, then you will also need android.permission.ACCESS_NETWORK_STATE in your Manifest (which is i.e. required by HttpUrlConnection client (see tutorial).

Addendum (2015-07-16)

Please note that Android 6 (aka Marshmallow) introduced completely new permission management mechanism called Runtime Permissions. It gives user more control on what permission are granted (also allows selective grant) or lets one revoke already granted permissions w/o need to app removal:

This [. ] introduces a new permissions model, where users can now directly manage app permissions at runtime. This model gives users improved visibility and control over permissions, while streamlining the installation and auto-update processes for app developers. Users can grant or revoke permissions individually for installed apps.

However, the changes do not affect INTERNET or ACCESS_NETWORK_STATE permissions, which are considered «Normal» permissions. The user does not need to explicitly grant these permission.

See behavior changes description page for details and make sure your app will behave correctly on newer systems too. It’s is especially important when your project set targetSdk to at least 23 as then you must support new permissions model (detailed documentation). If you are not ready, ensure you keep targetSdk to at most 22 as this ensures even new Android will use old permission system when your app is installed.

Источник

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();
}

Randika Vishman's user avatar

asked Jan 13, 2012 at 17:03

Mert's user avatar

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 Frankel's user avatar

Uriel FrankelUriel Frankel

14k8 gold badges45 silver badges67 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

Raphael Royer-Rivard's user avatar

answered Oct 22, 2015 at 23:52

Justin Fiedler's user avatar

Justin FiedlerJustin Fiedler

6,3723 gold badges20 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.

Community's user avatar

answered Mar 28, 2012 at 12:33

user462990's user avatar

user462990user462990

5,4443 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

rhaldar's user avatar

rhaldarrhaldar

1,06510 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.

Peter Mortensen's user avatar

answered Jan 17, 2013 at 9:14

Audrius Meškauskas's user avatar

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.

Peter Mortensen's user avatar

answered Nov 19, 2012 at 8:42

john's user avatar

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

Piroxiljin's user avatar

PiroxiljinPiroxiljin

5915 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

omzer's user avatar

omzeromzer

90010 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

jacoballenwood's user avatar

jacoballenwoodjacoballenwood

2,6722 gold badges22 silver badges38 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 Kaushik's user avatar

Atul KaushikAtul Kaushik

5,1533 gold badges28 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.

Peter Mortensen's user avatar

answered Nov 26, 2012 at 16:49

Tobias Reich's user avatar

Tobias ReichTobias Reich

4,8143 gold badges46 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

ZooS's user avatar

ZooSZooS

6388 silver badges15 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.

change_is_necessity's user avatar

answered Apr 6, 2016 at 22:53

Nourdine Alouane's user avatar

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

Darush's user avatar

DarushDarush

11k9 gold badges61 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.

Peter Mortensen's user avatar

answered Jul 19, 2014 at 16:52

Hamlet Kraskian's user avatar

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

ovenror's user avatar

ovenrorovenror

5324 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>

AbdulMomen عبدالمؤمن's user avatar

answered Dec 4, 2013 at 15:47

Prabakaran's user avatar

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

Mahdi Mehrizi's user avatar

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 Zhu's user avatar

Jason ZhuJason Zhu

731 silver badge6 bronze badges

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 Sur's user avatar

Santanu SurSantanu Sur

10.6k7 gold badges31 silver badges50 bronze badges

1

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

Peter Mortensen's user avatar

answered Nov 21, 2012 at 7:41

will's user avatar

0

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

Elad's user avatar

EladElad

1,44712 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

user2965003's user avatar

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

vovahost's user avatar

vovahostvovahost

32.5k15 gold badges110 silver badges109 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

lane's user avatar

lanelane

62315 silver badges18 bronze badges

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

Sergey Vyacheslavovich Brunov's user avatar

answered Apr 7, 2016 at 1:22

Zakir's user avatar

ZakirZakir

2,19219 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 Ege's user avatar

Yasin EgeYasin Ege

4633 silver badges10 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

Tarasantan's user avatar

TarasantanTarasantan

1,0458 silver badges6 bronze badges

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

answered Sep 23, 2021 at 11:24

Arpan24x7's user avatar

Arpan24x7Arpan24x7

6485 silver badges23 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 Li's user avatar

Guopeng LiGuopeng Li

711 silver badge9 bronze badges

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();
}

Randika Vishman's user avatar

asked Jan 13, 2012 at 17:03

Mert's user avatar

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 Frankel's user avatar

Uriel FrankelUriel Frankel

14k8 gold badges45 silver badges67 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

Raphael Royer-Rivard's user avatar

answered Oct 22, 2015 at 23:52

Justin Fiedler's user avatar

Justin FiedlerJustin Fiedler

6,3723 gold badges20 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.

Community's user avatar

answered Mar 28, 2012 at 12:33

user462990's user avatar

user462990user462990

5,4443 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

rhaldar's user avatar

rhaldarrhaldar

1,06510 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.

Peter Mortensen's user avatar

answered Jan 17, 2013 at 9:14

Audrius Meškauskas's user avatar

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.

Peter Mortensen's user avatar

answered Nov 19, 2012 at 8:42

john's user avatar

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

Piroxiljin's user avatar

PiroxiljinPiroxiljin

5915 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

omzer's user avatar

omzeromzer

90010 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

jacoballenwood's user avatar

jacoballenwoodjacoballenwood

2,6722 gold badges22 silver badges38 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 Kaushik's user avatar

Atul KaushikAtul Kaushik

5,1533 gold badges28 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.

Peter Mortensen's user avatar

answered Nov 26, 2012 at 16:49

Tobias Reich's user avatar

Tobias ReichTobias Reich

4,8143 gold badges46 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

ZooS's user avatar

ZooSZooS

6388 silver badges15 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.

change_is_necessity's user avatar

answered Apr 6, 2016 at 22:53

Nourdine Alouane's user avatar

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

Darush's user avatar

DarushDarush

11k9 gold badges61 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.

Peter Mortensen's user avatar

answered Jul 19, 2014 at 16:52

Hamlet Kraskian's user avatar

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

ovenror's user avatar

ovenrorovenror

5324 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>

AbdulMomen عبدالمؤمن's user avatar

answered Dec 4, 2013 at 15:47

Prabakaran's user avatar

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

Mahdi Mehrizi's user avatar

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 Zhu's user avatar

Jason ZhuJason Zhu

731 silver badge6 bronze badges

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 Sur's user avatar

Santanu SurSantanu Sur

10.6k7 gold badges31 silver badges50 bronze badges

1

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

Peter Mortensen's user avatar

answered Nov 21, 2012 at 7:41

will's user avatar

0

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

Elad's user avatar

EladElad

1,44712 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

user2965003's user avatar

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

vovahost's user avatar

vovahostvovahost

32.5k15 gold badges110 silver badges109 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

lane's user avatar

lanelane

62315 silver badges18 bronze badges

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

Sergey Vyacheslavovich Brunov's user avatar

answered Apr 7, 2016 at 1:22

Zakir's user avatar

ZakirZakir

2,19219 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 Ege's user avatar

Yasin EgeYasin Ege

4633 silver badges10 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

Tarasantan's user avatar

TarasantanTarasantan

1,0458 silver badges6 bronze badges

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

answered Sep 23, 2021 at 11:24

Arpan24x7's user avatar

Arpan24x7Arpan24x7

6485 silver badges23 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 Li's user avatar

Guopeng LiGuopeng Li

711 silver badge9 bronze badges

Отказ в разрешении

  1. Содержание.
  2. Используйте Android Vitals, чтобы оценить восприятие пользователями.
  3. Лучшие практики. Не запрашивайте ненужные разрешения. Отображение запроса на разрешение в контексте. Объясните, почему вашему приложению требуется разрешение.

Как включить разрешения на Android?

Включение или отключение разрешений

  1. На устройстве Android откройте приложение «Настройки».
  2. Коснитесь Приложения и уведомления.
  3. Коснитесь приложения, которое хотите обновить.
  4. Коснитесь Разрешения.
  5. Выберите, какие разрешения вы хотите иметь для приложения, например «Камера» или «Телефон».

Почему мне отказано в доступе к веб-сайту?

Проблема возникает, когда Firefox использует другие настройки прокси или VPN вместо того, что установлено на вашем компьютере с Windows. Когда веб-сайт обнаруживает, что что-то не так с файлами cookie вашей сети или браузера и т. Д., Он блокирует вас.

Как сбросить разрешения на моем Android?

Изменить разрешения приложения

  1. На телефоне откройте приложение «Настройки».
  2. Коснитесь Приложения и уведомления.
  3. Коснитесь приложения, которое хотите изменить. Если вы не можете его найти, сначала нажмите «Просмотреть все приложения» или «Информация о приложении».
  4. Коснитесь Разрешения. Если вы разрешили или запретили какие-либо разрешения для приложения, вы найдете их здесь.
  5. Чтобы изменить параметр разрешения, коснитесь его, затем выберите «Разрешить» или «Запретить».

Как исправить отказ в разрешении?

Чтобы заявить о праве собственности и удалить сообщение, вы должны иметь учетную запись администратора и использовать команду chown для изменения прав доступа к файлам.

  1. Откройте командный терминал. …
  2. Перейдите к файлу, который вы пытаетесь изменить. …
  3. Измените разрешения с помощью команды chown.

Что такое Permission denied?

Вы можете увидеть код ошибки, такой как 550, 553 или аналогичный, при попытке загрузить определенный файл на ваш сервер, что обычно означает, что файл / папка, которую вы пытаетесь развернуть, не принадлежит правильному пользователю или группе пользователей, или если папка в настоящее время используется другим процессом.

Как включить отключенные разрешения?

Удерживайте приложение телефона, пока не увидите небольшое «меню», в нем показаны несколько параметров и несколько ярлыков в приложении для телефона, нажмите «информация о приложении», затем откройте вкладку «разрешения» и включите отключенные один. Даже после предоставления всех разрешений контактные данные не открываются.

Что представляют собой опасные разрешения в Android?

Опасные разрешения — это разрешения, которые потенциально могут повлиять на конфиденциальность пользователя или работу устройства. Пользователь должен явно согласиться на предоставление этих разрешений. К ним относятся доступ к камере, контактам, местоположению, микрофону, датчикам, SMS и хранилищу.

Как включить разрешения для приложений?

Вот как это сделать.

  1. Для начала зайдите в «Настройки»> «Приложение» и найдите приложение, с которым вы хотите работать. Выберите это.
  2. Коснитесь Разрешения приложений на экране информации о приложении.
  3. Вы увидите список разрешений, запрашиваемых приложением, и информацию о том, включены ли эти разрешения. Коснитесь переключателя, чтобы настроить параметр.

18 юл. 2019 г.

Как мне пройти через сайты с отказом в доступе?

10 полезных методов доступа к заблокированным веб-сайтам

  1. Станьте анонимным, используя прокси-сайты. Очень часто в профессиональной среде работодатели устанавливают определенные границы, ограничивая ваш доступ к определенным веб-сайтам. …
  2. Подпишитесь на RSS-каналы. …
  3. Получайте веб-страницы по электронной почте. …
  4. Используйте IP, а не URL. …
  5. Обход через расширения. …
  6. Перенаправление с помощью службы коротких URL. …
  7. Кэш Google. …
  8. Используйте VPN.

18 колода 2020 г.

Как я могу открыть сайты, для которых запрещен доступ?

Как разблокировать сайты?

  1. Используйте VPN для разблокировки онлайн. …
  2. Разблокировщик веб-сайтов: используйте прокси-сайты. …
  3. Доступ к заблокированным сайтам в Chrome. …
  4. Используйте IP, а не URL. …
  5. Использовать Google Translate. …
  6. Обходите цензуру через расширения. …
  7. Замените свой DNS-сервер (Custom DNS)…
  8. Перейдите в Интернет-архив — Wayback Machine.

Почему мне отказали в доступе Nike?

Nike в Twitter: «Ошибка« Запрещенный доступ »обычно может быть исправлена ​​путем очистки кеша и файлов cookie вашего браузера.

Как очистить кеш Android?

В приложении Chrome

  1. На вашем телефоне или планшете Android откройте приложение Chrome.
  2. В правом верхнем углу нажмите на значок «Ещё».
  3. Коснитесь История. Очистить данные просмотра.
  4. Вверху выберите временной диапазон. Чтобы удалить все, выберите Все время.
  5. Установите флажки рядом с «Файлы cookie и данные сайтов» и «Кэшированные изображения и файлы».
  6. Коснитесь Очистить данные.

Как запретить приложениям Android доступ к личной информации?

Включение или отключение разрешений приложений по одному

  1. Перейдите в приложение «Настройки» вашего телефона Android.
  2. Нажмите на Приложения или Диспетчер приложений.
  3. Выберите приложение, которое вы хотите изменить, нажав «Разрешения».
  4. Отсюда вы можете выбрать, какие разрешения включать и выключать, например микрофон и камеру.

16 юл. 2019 г.

Безопасно ли давать приложениям разрешения?

«Нормальный» vs.

(например, Android позволяет приложениям получать доступ к Интернету без вашего разрешения.) Однако опасные группы разрешений могут предоставлять приложениям доступ к таким вещам, как история звонков, личные сообщения, местоположение, камера, микрофон и многое другое. Поэтому Android всегда будет просить вас одобрить опасные разрешения.

Exception open failed: EACCES (Permission denied) on Android

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.

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 dont 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

Exception open failed: EACCES (Permission denied) on Android

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.

Related posts on Android :

  • android – Programmatically Restart a React Native App
  • android – What does adb forward tcp:8080 tcp:8080 command do?
  • android – File.createTempFile() VS new File()
  • Kotlin-allopen for android
  • How to import Action Bar Sherlock? android studio
  • animation – Android – how to get android.R.anim.slide_in_right
  • android – Set notifyDataSetChanged() on Recyclerview adapter
  • adb – Android: adbd cannot run as root in production builds

Операционная система Android устроена таким образом, что для выполнения некоторых операций или доступа к определенным ресурсам, приложение должно иметь разрешение на это.

Разрешения могут быть двух типов: normal и dangerous. Отличие между ними в том, что dangerous разрешения опасны, т.к. могут быть использованы для получения ваших личных данных или информации о вас, или еще каким-то способом могут навредить вам. Примеры dangerous разрешений — это доступ к контактам или смс.

Полный список существующих разрешений можно посмотреть здесь. Характеристика Protection level подскажет насколько опасно это разрешение. А здесь можно сразу просмотреть весь список normal разрешений.

Если приложению необходимо получить какое-либо разрешение, то оно должно быть указано в AndroidManifest.xml, в корневом теге <manifest>. Тег разрешения — <uses-permission>.

Вот пример манифеста с разрешениями:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.someapplication">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.SEND_SMS" />

    <application
    ...
    ></application>

</manifest>

Здесь мы указываем, что приложению понадобятся разрешения на работу с интернет, контактами, bluetooth, локацией, камерой и смс. Пользователю необходимо будет подтвердить, что он предоставляет приложению эти разрешения.

В этом материале мы подробно рассмотрим, как происходит это подтверждение.

До Android 6

До выхода Android 6 все было просто и легко. Когда пользователь устанавливал приложение с манифестом, который мы рассмотрели чуть выше, то он видел такой экран:

Система показывает разрешения, которые были прописаны в манифесте. Сначала те, которые могут быть опасными с точки зрения приватности (отправка смс, доступ к камере/местоположению/контактам), а затем — обычные (интернет, bluetooth).

Таким образом пользователь видит, на что претендует приложение, и может примерно понять все ли в порядке. Если, например, приложение калькулятор при установке просит у вас доступ к контактам и смс, то скорее всего, что-то не так с этим приложением и оно может быть опасным для ваших данных.

Нажав кнопку Install, пользователь автоматически подтверждает свое согласие, что приложению будут предоставлены эти запрашиваемые разрешения. И далее, когда приложение, например, пытается в коде получить список контактов, то оно без проблем их получает.

Если же в манифесте не указать разрешение READ_CONTACTS, то его не будет и в списке тех разрешений, которые подтверждает пользователь. Соответственно, система не предоставит этому приложению доступ к контактам. И при попытке получить список контактов, будет ошибка:
java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2

Android 6

С выходом Android 6 механизм подтверждения поменялся. Теперь при установке приложения пользователь больше не видит списка запрашиваемых разрешений. Приложение автоматически получает все требуемые normal разрешения, а dangerous разрешения необходимо будет программно запрашивать в процессе работы приложения.

Т.е. теперь недостаточно просто указать в манифесте, что вам нужен, например, доступ к контактам. Когда вы в коде попытаетесь запросить список контактов, то получите ошибку SecurityException: Permission Denial. Потому что вы явно не запрашивали это разрешение, и пользователь его не подтверждал.

Перед выполнением операции, требующей разрешения, необходимо спросить у системы, есть ли у приложения разрешение на это. Т.е. подтверждал ли пользователь, что он дает приложению это разрешение. Если разрешение уже есть, то выполняем операцию. Если нет, то запрашиваем это разрешение у пользователя.

Давайте посмотрим, как это выглядит на практике.

Проверка текущего статуса разрешения выполняется методом checkSelfPermission

int permissionStatus = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);

На вход метод требует Context и название разрешения. Он вернет константу PackageManager.PERMISSION_GRANTED (если разрешение есть) или PackageManager.PERMISSION_DENIED (если разрешения нет).

Если разрешение есть, значит мы ранее его уже запрашивали, и пользователь подтвердил его. Можем получать список контактов, система даст нам доступ.

Если разрешения нет, то нам надо его запросить. Это выполняется методом requestPermissions. Схема его работы похожа на метод startActivityForResult. Мы вызываем метод, передаем ему данные и request code, а ответ потом получаем в определенном onResult методе.

Добавим запрос разрешения к уже имеющейся проверке.

int permissionStatus = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);

if (permissionStatus == PackageManager.PERMISSION_GRANTED) {
   readContacts();
} else {
   ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_CONTACTS},
           REQUEST_CODE_PERMISSION_READ_CONTACTS);
}

Проверяем разрешение READ_CONTACTS. Если оно есть, то читаем контакты. Иначе запрашиваем разрешение READ_CONTACTS методом requestPermissions. На вход метод требует Activity, список требуемых разрешений, и request code. Обратите внимание, что для разрешений используется массив. Т.е. вы можете запросить сразу несколько разрешений.

После вызова метода requestPermissions система покажет следующий диалог

Здесь будет отображено разрешение, которое мы запросили методом requestPermissions. Пользователь может либо подтвердить его (ALLOW), либо отказать (DENY). Если будет запрошено сразу несколько разрешений, то на каждое из них будет показан отдельный диалог. И пользователь может какие-то разрешения подтвердить, а какие-то нет.

Решение пользователя мы получим в методе onRequestPermissionsResult

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
   switch (requestCode) {
       case REQUEST_CODE_PERMISSION_READ_CONTACTS:
           if (grantResults.length > 0
                   && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // permission granted
               readContacts();
           } else {
               // permission denied
           }
           return;
   }
}

Проверяем, что requestСode тот же, что мы указывали в requestPermissions. В массиве permissions придут название разрешений, которые мы запрашивали. В массиве grantResults придут ответы пользователя на запросы разрешений.

Мы проверяем, что массив ответов не пустой и берем первый результат из него (т.к. мы запрашивали всего одно разрешение). Если пользователь подтвердил разрешение, то выполняем операцию. Если же пользователь отказал, то дальнейшие действия зависят от логики вашего приложения.

В итоге схема получения разрешения состоит из трех действий:
— проверка текущего состояния разрешения
— запрос на получение разрешения, если оно еще не было получено
— обработка ответа на запрос

Далее поговорим про некоторые дополнительные возможности, нюансы и прочие мелочи.

Манифест

При использовании новой схемы разрешений вам все равно необходимо указывать разрешение в манифесте. Если его там не указать и сделать запрос на это разрешение, то вам просто сразу придет отказ без всякого диалога.

Всегда проверяйте разрешение

Каждый раз (а не только первый) перед выполнением операции, требующей определенного разрешения, необходимо проверять, что это разрешение есть. Потому что, даже если пользователь уже давал это разрешение, он всегда может зайти в настройки приложения и отменить его. И если вы после этого не выполните проверку, то получите ошибку при выполнении операции.

Don’t ask again

Когда вы первый раз делаете запрос на какое-либо разрешение, пользователь может отказать. При последующих запросах этого же разрешения, в диалоге появится чекбокс Don’t ask again

Если пользователь включит этот чекбокс, то при последующих ваших запросах диалог не будет отображаться, а в onRequestPermissionsResult сразу будет приходить отказ.

Объяснение для пользователя

Когда вы запрашиваете разрешение, пользователю должно быть очевидно, зачем приложению понадобилось это разрешение, и у него не должно возникать вопросов. Но случаи бывают разные, и вы можете решить, что вам надо явно объяснить пользователю, почему приложению понадобилось это разрешение.

Диалог, который показывается при запросе разрешения, — системный, вы не можете менять его содержимое и добавлять туда свой текст. Но вы можете сделать свой диалог или что-то подобное и показать его перед тем, как будете делать запрос разрешения.

Есть метод shouldShowRequestPermissionRationale, который может быть полезен в данной ситуации. Передаете ему название разрешения, а он вам в виде boolean ответит, надо ли показывать объяснение для пользователя.

Т.е. вы сначала проверяете наличие разрешения. Если его нет, то вызываете shouldShowRequestPermissionRationale, чтобы решить, надо ли показывать объяснение пользователю. Если не надо, то делаете запрос разрешения. А если надо, то показываете ваш диалог с объяснением, а после этого диалога делаете запрос разрешения.

Алгоритм работы метода shouldShowRequestPermissionRationale прост.

Если вы еще ни разу не запрашивали это разрешение, то он вернет false. Т.е. перед первым запросом разрешения ничего объяснять не надо.

Если вы ранее уже запрашивали это разрешение и пользователь отказал, то метод вернет true. Т.е. пользователь не понимает, почему он должен давать это разрешение, и надо ему это объяснить.

Если пользователь ставил галку Don’t ask again, то метод вернет false. Запрос полномочий все равно не будет выполнен. Объяснять что-то не имеет смысла.

Разумеется, вы можете показывать дополнительную информацию согласно вашим правилам и не использовать метод shouldShowRequestPermissionRationale.

Группы

Dangerous разрешения собраны в группы. Список групп можно посмотреть здесь. Если вы запросили одно разрешение из группы и пользователь предоставил вам его, то вы автоматически получаете все разрешения этой группы.

Например, разрешения READ_CONTACTS и WRITE_CONTACTS принадлежат группе CONTACTS. И если пользователь уже подтверждал разрешение на READ_CONTACTS, то при проверке WRITE_CONTACTS вы получите PERMISSION_GRANTED.

Android 6 и targetSdkVersion 23

Схема работы разрешений зависит от версии Android, на которой запущено приложение и от параметра targetSdkVersion приложения.

Новая схема будет работать, если версия Android >= 6 И targetSdkVersion >= 23.

В остальных случаях, т.е. когда targetSdkVersion < 23 ИЛИ версия Android < 6, разрешения будут работать по старому. Т.е. пользователь будет подтверждать их сразу все при установке. Если в приложении есть код, который проверяет разрешения, то он будет получать PERMISSION_GRANTED.

Но учитывайте, что в Android версии 6 и выше, пользователь может отменить разрешения в настройках приложения.

Intent

Не забывайте, что иногда для работы с контактами, камерой и т.п., вы можете использовать Intent и уже установленные приложения. В этом случае вам не придется писать лишний код и запрашивать разрешения для работы с этими ресурсами.


Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance 

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня


Exception open failed: EACCES (Permission denied) on Android

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.

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 dont 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

Exception open failed: EACCES (Permission denied) on Android

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.

Related posts on Android :

  • android – Programmatically Restart a React Native App
  • android – What does adb forward tcp:8080 tcp:8080 command do?
  • android – File.createTempFile() VS new File()
  • Kotlin-allopen for android
  • How to import Action Bar Sherlock? android studio
  • animation – Android – how to get android.R.anim.slide_in_right
  • android – Set notifyDataSetChanged() on Recyclerview adapter
  • adb – Android: adbd cannot run as root in production builds

  • Ошибка performance warning бесконечное лето
  • Ошибка pdc failure bmw e60
  • Ошибка performance warning rust
  • Ошибка pcs тойота приус 30
  • Ошибка perfect world иероглифы