Permission denied reading from sdcard - android

I test my application on a virtual nexus 5 with Marshmallow
I got a notification about a virtual sd card being ready and I tried choosing both internal and external storage.
I uploaded a text file to sdcard/Download by dragging and dropping to the emulator.
I added <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> and even <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> to my manifest.
When I try to read a file a sd card using code such as this
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"Download/gradle.build");
try {
BufferedReader br = new BufferedReader(new FileReader(file))
...}
I get an open failed... EACCESS - permission denied exception thrown.
Why can't I read a file from the sdcard? Thanks.

Request permission at runtime is a feature added in android version 6.0 The idea is when the app is installed customers just grant permission without knowing the security risk. Dangerous permission must be granted at runtime so hopefully users know the risk, in this case you want to use SD storage because (give reason here). Good luck.

Since you are targetting devices marshmallow or above you have to give permissions at runtime and permissions declared in manifest does not mean anything. So have to give permission like below before accessing any of the file related read or write.
first check if permission already given by checking this
// Assume this Activity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck==PackageManager.PERMISSION_GRANTED){
//this means permission is granted and you can do read and write
}else{
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
}
here is permission guide

Related

Android API 28, save file in Download folder without user interaction

we're developping an app that will run as a service. One of the feature would be to download file at given URL (ex PDF) and save it into the download folder so user can load it from a specific application (Avenza Maps).
All the download process should be without any user interaction since it's by a service that run in the background.
i've added the following permission:
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<application
android:requestLegacyExternalStorage="true"
whatever i'll try i got the following error
java.io.FileNotFoundException: /storage/emulated/0/Download/name.pdf (Permission denied)
how can i get the permission to write on Download folder (this is system Download folder)
without having to open an activity to save the file?
i'll try multiple solution yet(2 day of google) without success
for now as stated we target API 28 (android 9)
we will later target other API since we provide the device to the client so we develop only for the API our device have.
I've recently had to develop an app that downloads voice files to a device. While you can specify permissions in the Android manifest, you must request permissions from the user. I've done so in Java, but a conversion to Kotlin should be simple.
//method is called to check the storage permissions for this app
//ensures the app can write and read files
private void checkStoragePermissions() {
Log.i("Permissions", "Checking Storage Permissions");
int writePermissionCode = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);//get current write permission
int readPermissionCode = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);//ge current read permission
Log.i("Permissions", "Fetching Read & Write Codes: " + readPermissionCode + "/" + writePermissionCode);
//if permissions to read and write to external storage is not granted
if (writePermissionCode != PackageManager.PERMISSION_GRANTED || readPermissionCode != PackageManager.PERMISSION_GRANTED) {
//request read and write permissions
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PackageManager.PERMISSION_GRANTED);
Log.i("Permissions", "Asking For Storage Permissions");
} else {//else: if permissions to read and write is already granted
permissionsGranted = true;//set permissions granted bool to true
}
}
After you've done this the downloading of the files can be done in many ways. It's worth noting that files can't be downloaded to any location on an Android device. Only a specific destinations can be used.
I hope this helps to clear some of your confusion. Happy coding!
how can i get the permission to write on Download folder (this is system Download folder) without having to open an activity to save the file?
The simplest solution is to write somewhere else, where you do not need permissions. The methods on Context that return File objects, like getFilesDir() and getExternalFilesDir(), are your primary candidates.
Beyond that, it appears that your app is pre-installed on some device ("we provide the device to the client"). If you have developed a custom firmware image, you should be able to pre-grant the permission to your app as part of that image. Or, if the device is being distributed already configured (no first-time-power-on onboarding UI), you could manually grant WRITE_EXTERNAL_STORAGE to your app or have a UI automation script do it.
If none of those are options, then you have no choice but to ask the user for permission.

Failed to Save Files on Storage [FileSystemException] Flutter

I uploaded an android photo compress application in play store and I checked every thing is ok, but some users have issue that the application can not save compressed photos, I checked that and I found this error
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot create file, path = '/storage/emulated/0/My Folder/photo.jpg' (OS Error: Operation not permitted, errno = 1)
This is permissions AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
<uses-permission android:name="android.permission.CAMERA"/>
This line inside application tag
android:requestLegacyExternalStorage="true"
I looked for some solutions and founded this permission line
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
But when ask for this permission android shows to user warning the application will access to all files without asking permission, I feel this is worrying for users and some may be afraid of this permission, however I uploaded the application but it was rejected because using MANAGE_EXTERNAL_STORAGE permission.
you are right regarding MANAGE_EXTERNAL_STORAGE permission. Your app will be removed from play store if you don't have valid reasons. You may have to create a video and explain why you need these permission, and how scoped storage can't help you.
Now, you should know one thing that you are trying to create a folder directly inside internal storage. This will work in lower android versions but will fail in Android 10 or above even when you have WRITE_EXTERNAL_STORAGE granted.
Try creating your files inside public directories like Download or Documents. If the files downloaded doesn't need to be accessed by users then you can always save in your package folder context.getExternalFilesDir(null)
Hope this helped you! If you have any further doubts feel free to comment down below.

Can not read a file using in Xamarin forms using Pcl Storage

I am trying to read a video file which is in byte array using PCL Storage. So I have added the video file in the folder named File using android studio tool. Trying to read from there. The thing is that in my code it can find out that the file exists in the folder but whenever I am trying to read it using the following code I am getting an exception: "Access denied" but I have already enabled the permission in android manifest for reading and writing from external storage
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFile files = await rootFolder.GetFileAsync("myVideo.Mp4");
var text = await files.ReadAllTextAsync();
I am getting an exception: "Access denied" but I have already enabled the permission in android manifest
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. You should request permissions at runtime.
System permissions are divided into two categories, normal and dangerous:
Normal permissions do not directly risk the user's privacy. If your app lists a normal permission in its manifest, the system grants the permission automatically.
Dangerous permissions can give the app access to the user's confidential data. If you list a dangerous permission, the user has to explicitly give approval to your app during the runtime of the app.
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider ... requires android.permission.READ_EXTERNAL_STORAGE
READ_EXTERNAL_STORAGE is categorized as Dangerous permissions, so you should check this permissions manually for API level 23 and above.
Update:
Here is an example that request permissions at runtime.

Check file existence without permissions request

I found that I can check file existence (method file.exist()) on Android 7 in external storage without permission request popup for READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions.
I have WRITE_EXTERNAL_STORAGE in manifest but I don't show permission popup. And when I do file.exist() I have no any exception. Of course I have exception when try read this file.
Is this normal behavior? Can I expect that this work same on another devices. As for me this is strange that I can check file existence without requesting user.

Why is READ_EXTERNAL_STORAGE permission request not needed to read file from external storage?

I'm testing my app on an emulator. I have an export function where I create and write to a file in the external storage's downloads directory. And I also have an import function where I read a file from the external storage's downloads directory.
From Android documentation:
If the device is running Android 5.1 or lower, or your app's target SDK is 22 or lower: If you list a dangerous permission in your manifest, the user has to grant the permission when they install the app; if they do not grant the permission, the system does not install the app at all.
If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.
My emulator is running on Android 6.0 and my app's target SDK is 25, therefore I must also request each dangerous permission it needs while the app is running. I did so for the export functionality and everything works properly. However, when I'm implementing the import function I didn't request a permission during runtime. And the strange thing is I'm still able to read from my external storage's permission without READ_EXTERNAL_STORAGE being requested and granted at runtime. READ_EXTERNAL_STORAGE is a dangerous permission according to this Android documentation .
To verify, I made sure to disable permissions before I started using the feature and after it is completed, I verified again that the permission still wasn't granted. Although I'm happy with the behaviour since it's working without me requesting permission at runtime, but according to the documentations I don't believe this behaviour is expected. That's why I will like to know what's causing this and to figure out the problem before I publish any changes for the app.
Here's a code snippet of my manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The code snippet where I pick a file to read:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/*");
startActivityForResult(intent, GET_FILE_RESULT_CODE);
The code snippet where I read the file chosen from the code snippet above (exportFile is simply the URI from onActivityResult):
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(context.getContentResolver().openInputStream(exportFile)));
String line;
// Skip first header line
br.readLine();
while ((line = br.readLine()) != null) {...}
Thanks!
There's a well explanation here,
READ_EXTERNAL_STORAGE
Provides protected read access to external storage. In Android 4.1 by
default all applications still have read access. This will be changed
in a future release to require that applications explicitly request
read access using this permission. If your application already
requests write access, it will automatically get read access as well.
There is a new developer option to turn on read access restriction,
for developers to test their applications against how Android will
behave in the future.
In short, READ_EXTERNAL_STORAGE only exists as of Jelly Bean (Level 16). So, unless you're using a Jelly Bean phone and set the developer option "Protect USB storage" it won't be a problem.
You know,Android Runtime Permissions are grouped, since you applied for WRITE_EXTERNAL_STORAGE permission in the manifest already, so there's no need to apply for READ_EXTERNAL_STORAGE permissions.Both of them are the same group.

Categories

Resources