Accessing external storage in Android API 29 - android

I'm trying to achieve some clean up tools. More and more manufacturers have forbidden rooting devices due to some "security reason", it's forbidden NOT to request for unlock.
After API 28, This code will make error:
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 1); // Request permission or not, Will got same result
File rootFolder = Environment.getExternalStorageDirectory(); // That is working fine
rootFolder.listFiles(); // That will return null
Sure, I can use this:
android:requestLegacyExternalStorage="true"
But I belive that will be killed in future.
So, Any elegant way to manage SDCard?

On Android 10 Environment.getExternalStorageDirectory() and Environment.getExternalStoragePublicDirectory() will return storage paths but paths are not readable or writable.
For Android 10 you can continue to use paths provided by Environment.getExternalStorageDirectory() and Environment.getExternalStoragePublicDirectory() if you add android:requestLegacyExternalStorage="true" to application tag in manifest file. At runtime your app can call Environment.isExternalStorageLegacy() to check if the request has been done.
Another (not known) possibility (only for Android 10) is to add <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> to manifest file.
The user has to go to the advanced settings of the app and enable from Advanced settings Install unknown apps | Allow from this source.
The nice thing with this is that the user can switch the access rights. You can make it easier for the user if you implement an intent for
Settings.ACTION_APPLICATION_DETAILS_SETTINGS where he can change the settings.
A funny thing is that Environment.isExternalStorageLegacy() returns true then too.
Compiling for Android 11 both options do not work on an Android 11 device. (But they continue to work for Android 10 devices). The paths of Environment.getExternalStorageDirectory() and Environment.getExternalStoragePublicDirectory() are usable again in read mode and very often in write mode too. And this is great as one can simply list the contents of directories like Download or Pictures or DCIM/Camera again using the File class.
But adding <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> to manifest file and implementing an intent for
Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION will give your app read/write access for all files even on removable micro sd card.
(Finally you can remove the google ban not being able to read/write your own micro sd card on your own Android device using your own app).
Environment.isExternalStorageManager() can be used to check if the permission is on/off.
As long as you do not try to upload your app to the play store you are fine.

use android:requestLegacyExternalStorage="true" in your Manifest below <application

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.

java.io.FileNotFoundException: /storage/emulated/0/Download/myFile.pdf: open failed: EACCES (Permission denied)

Since Android Q came out there are some privacy changes in the permissions about read from external storage. I have a chat application that the user can choose a photo from Downloads etc... and send it. So i need to have access to that files. The way i did this is by using contentProvider.
context.contentResolver.openInputStream(uri)?.use { inputStream ->
while (true) {
numBytesRead = inputStream.read(buffer)
// .. do stuff
}
}
The uri that is available at that time is -> file:///storage/emulated/0/Download/myFile.pdf
However i get a FileNotFoundException but the file trully exists.
I have set all the permissions in the manifest and granted them on the launch of the app. From Android <= 9 it works properly.
So what do i have to do...?
I have a chat application that the user can choose a photo from Downloads etc... and send it
That will not be possible on Android 10 and higher. You need to switch to something else. For example, you could use ACTION_OPEN_DOCUMENT to allow the user to choose content from anywhere the user wants. Then, use the resulting Uri to upload it to your chat server, akin to how you are using the Uri in your code snippet. Or, better yet, don't read it all into memory — use something like this OkHttp InputStreamRequestBody implementation.
For Android 10, you can add android:requestLegacyExternalStorage="true" to your <application> element in the manifest. This opts you into the legacy storage model, and your existing external storage code will work. That will not work on Android R and higher, though, so this is only a short-term fix.

Reading Folder Structures on Android SD Card

I am new to Xamarin Android, but have some experience with C# and WinForms. I have a modern Android device using Android 9. I can use the built-in File Manager to see my SD card. I can also use that app to create a folder on my SD card (for example "Test Folder"). What I have not been able to do is access that folder using my C# Xamarin Android code. Should I be able to, or is this frowned upon? Is there a generic solution that will work on other devices that also have an SD card?
The Android.OS.Environment.GetExternalStoragePublicDirectory method does not seem to recognize the presence of the removable, external storage. I have also tried
new Intent(Intent.ActionOpenDocumentTree);
This allows me to "see" the new folder, but I can't seem to do anything with the URI that I get back.
To create Folder in External Storage (if External Storage is available otherwise it creates in internal storage)
public void createMainFolder (){
String myfolderLoc=Environment.getExternalStorageDirectory()+"/"+yourFolderName;
File f=new File(myfolderLoc);
if(!f.exists()) {
if (!f.mkdir()) {
//folder can't be created
} else {
//folder has been created
}
}
}
And to get the path of the folder :
public String getAppmainFolderName(){
return Environment.getExternalStorageDirectory()+"/"+yourFolderName;
}
Don't forget to add Storage Permission in your manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and check Storage Permission is granted or not before accessing your External Storage (required for android 6.0 and above).
Request App Permission Android Doc.
Hope this will help you. 🙂

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.

Android Shared Internal Storage

Is there such thing on any Android based device as shared internal storage? I know you can use the SDCard as a shared file location between applications, but for a project I'm working on we dont want the ability for a SD Card to go missing (sensitive material).
The problem is as follows. App1 allows a user to browse (for example) some word documents and download them to the proposed shared storage, the user can then pass this file to Documents 2 Go editing them and saving the change. App 1 then allows an upload of the changed file.
I don't fancy building a document editor word/excel directly into app, unless thats easy?
EDIT:
The second app is "Documents 2 Go" I won't be able to edit its AndroidManifest
I faced a similar situation now for txt files and did this.
File downloadedFile= new File( context.getFilesDir(), "simple.txt" );
downloadedFile.setReadable( true, false );
downloadedFile.setWritable( true, false ); //set read/write for others
Uri downloadFileUri = Uri.fromFile( downloadedFile );
Intent intentToEditFile = new Intent( Intent.ACTION_EDIT );
intentToEditFile.setDataAndType( downloadFileUri, "text/plain" );
context.startActivity( intentToEditFile );
Now the 'Document 2 Go' editor will be launched to edit the file and
will be able to edit simple.txt
Note 1: Uri should be created from same file object that was set with
setReadable()/setWritable.
Note 2: Read/Write permission for other users might not be reflected in file
system. Some times I cannot see rw-rw-rw- in adb shell
I believe ContentProviders is your solution. Its the Android recommended method for sharing application data between different apps.
https://stackoverflow.com/a/6708681/804447
Sharing data between apps is what ContentProviders are for. Assuming that you know how to write a ContentProvider and access it, you can access files via ParcelFileDescriptor, which includes constants for the mode in which you create the files.
What you need now is to limit access so that not everybody can read the files through the content provider, and you do that via android permissions. In the manifest of one your apps, the one that will host the files and the content provider, write something like this:
<permission android:name="com.example.android.provider.ACCESS" android:protectionLevel="signature"/>
and in both apps add this:
<uses-permission android:name="com.example.android.provider.ACCESS" />
by using protectionLevel="signature", only apps signed by you can access your content provider, and thus your files.

Categories

Resources