Flutter Android 11 permissions like WhatsApp - android

I'm trying to build a Flutter application that runs on Android 11 and downloads files. I used to manage external storage permission to achieve this, but when the application asks for permission it goes to settings directly instead of asking for allow or deny within the app.
For example, WhatsApp stores data in the android/media folder, but it asks for permission directly within the application instead of going to the settings page. Please refer the below images:
My application goes to settings like this / I need something like this
My permission handling code
Future<bool> requestPermission() async {
var androidInfo = await DeviceInfoPlugin().androidInfo;
var release = int.parse(androidInfo.version.release);
Permission permission;
if (release < 11) {
permission = Permission.storage;
} else {
permission = Permission.manageExternalStorage;
}
if (await permission.isGranted) {
return true;
} else {
var result = await permission.request();
if (result == PermissionStatus.granted) {
return true;
} else {
return false;
}
}
}

These are two different approaches to manage the access the external storage in the Android device for Android 11 and above.
Files Go is trying to access the all files access permission. This gives app to access any read, write, access and share all files present in user storage(external or internal).
You can read more about all files access permission from here - Manage all files on a storage device
WhatsApp - instead of asking for all files access permission, is saving its media in files directory. Saving in the files or cache directory doesn't need access to all flies and a simple permission dialog to write and read storage does the task.
You can read more about it in getExternalFilesDir.
Note: This only applies if your targetSdkVersion is 30. Targeting a 29 or below version, there isn't any need to all files permission as it's handled by the system.
You can refer to storage updates and request permission according to your use case in Storage updates in Android 11.

Even if you are in Android 11 or above we have to ask the storage permission not the manage external storage permission in Flutter. I tried to write the files to 'android/media/packagename/' and it is working normally, but when I try to write into other locations it's not working. I think somehow Android internally is allowing to store data only in the same package.

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.

Android 13 - How to request WRITE_EXTERNAL_STORAGE

I am targeting my Android app for Android 13 (API 33)
The WRITE_EXTERNAL_STORAGE permission seems to be working fine below API 33 i.e. Android 12 and less but the runtime permission popup for WRITE_EXTERNAL_STORAGE won't appear when running the app on Android 13.
My Android app creates one keystore file in app's private storage.
The behaviour changes for Android 13 mention this:
If your app targets Android 13, you must request one or more new
permissions instead of the READ_EXTERNAL_STORAGE.
The new permissions are:
Images and photos: READ_MEDIA_IMAGES
Videos: READ_MEDIA_VIDEO Audio
Audio files: READ_MEDIA_AUDIO
I didn't find any information about this in the official documentation.
The documentation is focusing on media files only without any word about other file types.
https://developer.android.com/about/versions/13/behavior-changes-13#granular-media-permissions
TLDR: You don't.
From Google's official documentation:
"If your app targets Android 11, both the WRITE_EXTERNAL_STORAGE permission and the WRITE_MEDIA_STORAGE privileged permission no longer provide any additional access."
So in effect, if you were to request WRITE_EXTERNAL_STORAGE on Android 11 or later, you would be requesting nothing. This is the whole point of Android's migration to scoped storage, which effectively prevents apps from reading or writing to the storage directories of other apps UNLESS they are accessing specific file types (e.g. media, using the permissions you mentioned) or are granted special file manager permissions by Google themselves. For more insight into scoped storage, see this well written article, but TLDR security and leftover files from app uninstalls were the big reasons Google did this.
So if you really want to write files, either make sure you're only writing to your app's designated storage directories, in which case you won't need any permissions at all, or if you really need to write to a directory your app doesn't own get that file manager permission from Google (how to get that permission)
You can find documentation for accessing non-media files at Android official documentation or "How to Save a File in Shared Storage Location in Android 13". From Android 10 onwards, if you want to write a file which is intended to be accessible directly by other apps (such as File manager) or user, then you have to write it onto Shared Storage location. This has to be done in 3 steps:
Step 1: Launch System Picker to choose the destination by the user.
private ActivityResultLauncher<Intent> launcher; // Initialise this object in Activity.onCreate()
private Uri baseDocumentTreeUri;
public void launchBaseDirectoryPicker() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
launcher.launch(intent);
}
Step 2: Receive the chosen destination as Uri returned by System Picker in onActivityResult(). Here, you can optionally persist the permissions and Uri for future use.
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
baseDocumentTreeUri = Objects.requireNonNull(result.getData()).getData();
final int takeFlags = (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// take persistable Uri Permission for future use
context.getContentResolver().takePersistableUriPermission(result.getData().getData(), takeFlags);
SharedPreferences preferences = context.getSharedPreferences("com.example.fileutility", Context.MODE_PRIVATE);
preferences.edit().putString("filestorageuri", result.getData().getData().toString()).apply();
} else {
Log.e("FileUtility", "Some Error Occurred : " + result);
}
}
Step 3: Write content into a file.
public void writeFile(String fileName, String content) {
try {
DocumentFile directory = DocumentFile.fromTreeUri(context, baseDocumentTreeUri);
DocumentFile file = directory.createFile("text/*", fileName);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(file.getUri(), "w");
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
}
}

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.

Permission to Access External Storage Denied in AndroidTest

Before I begin explaining my question, I have to mention that I am new to Android development.
I am trying to write a program for Android which uses OpenCV's Java API for some data processing. I am developing unit tests for classes that implement algorithms and these classes are not related to any activity yet. In other words, I just want to test the functionality of methods before dealing with activities.
Because I need to have access to OpenCV libraries, I have written my unit test under androidTest in Android Studio. The files that contain data and need to be read in the program are copied to /sdcard/DIR and /storage/emulated/0/DIR. I have added the following permission to AndroidManifest.xml to grant access to external storage.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
However, when I try to read files from external storage I get
open failed: EACCES (Permission denied). Note that I concatenate the path returned by Environment.getExternalStorageDirectory().getAbsolutePath() with the name of data files and use a FileInputStream later on to read contents of the files.
I have seen similar questions and answers that mention access should be granted at runtime for APIs above 23. But because I don't have any activities for my methods, I guess I can't request permission at runtime.
Are there any other directories I can use to place my data files that do not require these permissions? I thought of assets as an option, but I am assuming that assets are put in the final apk and if I need to change files for a different data, I have to create a new apk every time.
How should I grant access to /sdcard without having any activity that asks user for a permission at runtime?
Can I do local testing instead of androidTest by installing OpenCV libraries on my linux machine?
Sorry but android doesn't provide that type of access
you will need to create a activity to launch the application
I think if you are using marshmallow device then you will be needing to ask the permission to read and write external storage at runtime
you can refer at the following liink
https://developer.android.com/training/permissions/requesting.html
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==
PackageManager.PERMISSION_GRANTED) {
//do the things} else {
requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
AnyNumber);
Later catch those requests in
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == AnyNumber) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
}
}
}
I found a temporary workaround for this issue. I designed a button in MainActivity that when pressed, asks user for permission to access the directory where my files are located at. Afterwards, I could run the androidTest unit tests without facing the exception because this permission needs to be granted only once.

how to get secondary storage uri or root directory of secondary storage of all devices in android

the secondary storage access is the main problem in android for all device but why?if anyone can solve this then it will be very helpful to me.who can know about access of secondary storage means external sd card of any device in marshmallow.please check below code link and help me.Its big problem still don't get solution.
https://www.dropbox.com/s/sojccopr46gbqgg/CheckExternalSDCardDemo.tar.gz?dl=1
before you access the external storage or root storage you need to define user permission in manifest and as well as in java file of your code where you want to access it before this ask the run time permission for external storage
for adding run time permission go threw https://developer.android.com/training/permissions/requesting.html
or any run time tutorial
First, check whether External Storage is Available or Not using below code:
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
If it returns true use below code to get access to External Storage:
getExternalStoragePublicDirectory()
For more information visit: Official Documentation

Categories

Resources