on android api 34 why dont work Intent.ACTIONOPENDOCUMENT and Intent.ACTIONCREATEDOCUMENT?
- User
on android api 34 why dont work Intent.ACTION_OPEN_DOCUMENT and Intent.ACTION_CREATE_DOCUMENT?
- Assistant
As of my last update, Android API 34 indeed should still support
Intent.ACTION_OPEN_DOCUMENTandIntent.ACTION_CREATE_DOCUMENTas these are key components of Android's storage access framework intended for better user privacy and control over files. If you're encountering issues where these intents don't seem to work, there could be several reasons based on implementation errors, permission issues, or other runtime problems. Let's troubleshoot a few common issues:1. Ensure You're Using the Correct Intent and Request Codes
When handling file creation or access, make sure you're setting up your Intents correctly:
// For opening a document Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("*/*"); // Set MIME type as per your requirement startActivityForResult(intent, OPEN_DOCUMENT_REQUEST_CODE); // For creating a document Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("application/pdf"); // Set MIME type as per your requirement intent.putExtra(Intent.EXTRA_TITLE, "newfile.pdf"); startActivityForResult(intent, CREATE_DOCUMENT_REQUEST_CODE);2. Check for Proper Permissions
Ensure that you have requested the necessary permissions in your
AndroidManifest.xmland, for sensitive permissions or if targeting Android 6.0 (API level 23) and above, ensure you also handle runtime permission requests.<!-- Add these permissions in the AndroidManifest.xml --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!-- Android 10 (API level 29) and above doesn't require WRITE_EXTERNAL_STORAGE if you're using scoped storage -->Remember, for accessing photos, media, or files in Android 10 (API 29) or later, consider using scoped storage practices without needing any permissions, unless you're requesting access to the whole storage with
MANAGE_EXTERNAL_STORAGE.3. Check Android Version Specific Behaviors
New versions of Android might change how storage access works. Starting from Android 10 (API level 29), scoped storage is enforced, and direct file path access is limited. Make sure your code respects these limitations.
4. Handle the Activity Result Properly
When your user selects a file or creates a new one, handle the result in
onActivityResult():@Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (requestCode == OPEN_DOCUMENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) { // handle opening the document Uri uri = null; if (resultData != null) { uri = resultData.getData(); // Perform operations on the uri (like opening the file) } } if (requestCode == CREATE_DOCUMENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) { // handle the creation of the document Uri uri = null; if (resultData != null) { uri = resultData.getData(); // Use a FileOutputStream to write to the uri } } }5. Are There Any Logcat Errors?
Checking the Logcat outputs in your development environment might provide insights into what could be going wrong. Watch for exceptions or error logs that could point out what's missing or misconfigured.
6. API Level Checks
Make sure that your app's targeted API levels in
build.gradle(minSdkVersion and targetSdkVersion) are appropriately set to support the functionality you are using.If everything seems correct but you're still facing issues, it might be a bug or a device-specific problem. Testing on different devices or emulators with different API levels might help you further pinpoint the issue.
- User
About item 5 i printed to logcat win function:
public boolean isPermissionsGranted() { Log.d(TAG, "isPermissionsGranted()"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { boolean write = ContextCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; boolean read = ContextCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; System.out.println("[aar-plugin] isPermissionsGranted 1 " + String.valueOf(read) + " " + String.valueOf(write)); return (read && write); } else { System.out.println("[aar-plugin] isPermissionsGranted true 2"); return true; } }On request permission this function prints both "false" values of "write" and "read"variables.
- Assistant
From your description, it appears you are correctly detecting that the necessary permissions (
WRITE_EXTERNAL_STORAGEandREAD_EXTERNAL_STORAGE) are not granted on Android API 34 (Android 13, codenamed Tiramisu), hence returning "false" in your logging statements.Starting with Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. Additionally, with scoped storage introduced in Android 10 (API level 29) and enforced further in newer versions, the necessity and behavior of these permissions have significantly changed.
In Android 13 (API 34), the access to broad storage via
WRITE_EXTERNAL_STORAGEorREAD_EXTERNAL_STORAGEmight be further restricted or differently managed due to ongoing privacy enhancements and changes in storage management.Steps to Request Runtime Permissions:
You need to handle the request for permissions at runtime, properly. If the permissions are not granted, you must explicitly request them from the user. Here's how you can do this:
- Modify
isPermissionsGranted()to only check permissions: Continue to use this function to check if permissions are granted before performing any actions that require them.
public boolean isPermissionsGranted() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // From Marshmallow boolean write = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; boolean read = ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; Log.d(TAG, "[aar-plugin] Permissions Read: " + read + ", Write: " + write); return (read && write); } return true; // Pre-Marshmallow, permissions are granted at install time }- Request the necessary permissions at runtime if not granted: You should prompt the user for permission if they are not granted:
private void requestPermissions() { if (!isPermissionsGranted()) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } }- Handle the permission result:
Override the
onRequestPermissionsResultto handle the user's response to the permission requests.
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSION_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { // Permissions granted. You can perform the action requiring these permissions. } else { // Permissions denied. Handle the functionality restriction or explain the user why this permission is necessary. } } }Points to Note:
- Rethink Using Scoped Storage: Depending on your application's requirement, consider moving towards using scoped storage which doesn't require broad storage permissions.
- Manifest Declarations: Although you declare permissions in the Android manifest, runtime permission requests are necessary from Android 6.0 onwards.
- Educate Your Users: When requesting permissions, especially sensitive ones which access user data, it's good practice to explain why these permissions are necessary either before or during the permission request flow.
Following these steps should help handle permissions correctly and address the issues you're facing on devices running Android API 34 (Android 13).
- Modify
- User
in that code structure after call "requestPermissions" why function "onRequestPermissionsResult" returns grantResults[0] as 0 (i.e. READ_EXTERNAL_STORAGE as PERMISSION_GRANTED), but grantResults[1] as -1 (i.e. WRITE_EXTERNAL_STORAGE as PERMISSION_DENIED)?
- Assistant
If
onRequestPermissionsResultreturnsPERMISSION_GRANTED(0) forREAD_EXTERNAL_STORAGEbutPERMISSION_DENIED(-1) forWRITE_EXTERNAL_STORAGE, it typically indicates a few possible scenarios related to how Android handles permissions, particularly as the OS version evolves:1. Changes in Permissions with Android Versions
Starting from Android 10 (API level 29), the
WRITE_EXTERNAL_STORAGEpermission was effectively deprecated as Google moved towards enforcing scoped storage. By Android 11 (API level 30), applications are expected to use scoped storage by default, and broad file system access is not generally allowed unless you hold theMANAGE_EXTERNAL_STORAGEpermission, which is intended for apps that genuinely need access to manage files across the entire storage (like file managers).Given you're developing for Android 13 (API 34), here's why you might encounter issues:
- Scoped Storage Enforcement: On devices running Android 10 and above, the system ignores the
WRITE_EXTERNAL_STORAGEpermission because it is no longer relevant with scoped storage enforced. Scoped storage allows you to save and manipulate your app's files in its private directory without requesting any permissions. You can also access shared storage (like the Media Store for images, videos, etc.) using respective MediaStore APIs without needing broad filesystem permissions.
2. Requesting Permissions
If your targetSdkVersion is set to 29 or higher, you should consider adopting scoped storage principles fully, unless you have a valid use case for requesting
MANAGE_EXTERNAL_STORAGE(which involves Android showing a system settings screen where the user has to manually allow access due to the sensitive nature of this permission).- Implications for Your App:
- If you need to access, create, or edit documents or media files that appear in system pickers, consider using
ACTION_OPEN_DOCUMENT,ACTION_CREATE_DOCUMENT, and other such intent actions, which do not require any storage permissions. - For manipulating non-media files or working with files in a more controlled environment (like downloading files through network and saving), use the app-specific storage directories (
getFilesDir(),getCacheDir()) or use external caches (getExternalCacheDirs(),getExternalFilesDirs(String type)).
- If you need to access, create, or edit documents or media files that appear in system pickers, consider using
Steps Moving Forward:
- Reassess Permission Requirements: Consider whether you need
WRITE_EXTERNAL_STORAGEor you can achieve your functionality using scoped storage practices. - Update Your Permissions Request: If continuing with broad file access (not recommended for most cases):
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); intent.addCategory("android.intent.category.DEFAULT"); intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName()))); startActivityForResult(intent, REQUEST_CODE_PERMISSION_MANAGE_STORAGE); } else { // Request for WRITE permission here for older Android versions ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE_PERMISSION); } - Educate Users: If you do need sensitive permissions like
MANAGE_EXTERNAL_STORAGE, clearly explain why through UI elements or dialogs before directing them to settings.
By understanding these elements, your app will be better positioned for compatibility with current and future Android versions, enhancing user trust and security.
- Scoped Storage Enforcement: On devices running Android 10 and above, the system ignores the
- User
Yes, i really need possibility to save file to external storage (just copy from app's internal dir to "Downloads" dir for example). In this case do i need to request WRITE_EXTERNAL_STORAGE on android apis greater than API 30 (android R)? On API 30+ how can i save file through Intent.ACTION_CREATE_DOCUMENT?
- Assistant
If you need to save files to a location like the "Downloads" directory on Android API 30+ (Android R and later), it's recommended to use the Storage Access Framework (SAF) which provides a more user-friendly and secure way to handle files via system file picker UIs. Using SAF, you can create and save files in user-selected directories without needing to request the
WRITE_EXTERNAL_STORAGEpermission.Here's how you can save a file to the "Downloads" directory or any other user-specific directory using
Intent.ACTION_CREATE_DOCUMENT:Step 1: Launch the System File Picker
You can direct the user to save a file using the system's file picker interface using
Intent.ACTION_CREATE_DOCUMENT. Here's how to start this intent, which lets the user specify the filename and choose the storage location:private void createFile() { Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); // Filter to only show results that can be "opened", such as a file (as opposed to a list of contacts or time zones). intent.addCategory(Intent.CATEGORY_OPENABLE); // Create a file with the requested MIME type. You can modify this based on the type of file you're creating (e.g., text/csv, application/pdf, image/jpeg). intent.setType("application/pdf"); intent.putExtra(Intent.EXTRA_TITLE, "newfile.pdf"); startActivityForResult(intent, CREATE_FILE_REQUEST_CODE); }Step 2: Handle the File Creation
After the user selects the location and confirms the saving action, you'll handle the output in your
onActivityResult()method. Here, you'll receive an URI that represents the location where the file should be written:@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CREATE_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK) { if (data != null && data.getData() != null) { Uri uri = data.getData(); try { writeContentToUri(uri); } catch (IOException e) { // Handle error here e.printStackTrace(); } } } } private void writeContentToUri(Uri uri) throws IOException { try (OutputStream outputStream = getContentResolver().openOutputStream(uri)) { if (outputStream != null) { outputStream.write(/* your data here */); outputStream.flush(); } } }Ensure you modify
writeContentToUri()to handle the specific type of content you're writing.Key Points:
- No Need for Storage Permissions: Using
Intent.ACTION_CREATE_DOCUMENT, you don’t need any permission to write to the file in the directory chosen by the user via the file picker. This applies even if the user chooses external storage locations like the "Downloads" folder. - User Privacy: This approach inherently respects user privacy and control, as the user explicitly chooses where the file is to be saved.
- Compatibility and Best Practices: Using SAF ensures that your app remains compatible with future Android versions and conforms to Android's recommended best practices for file storage.
By using the Storage Access Framework, your application can seamlessly integrate with Android's secure storage methodologies while offering a positive user experience.
- No Need for Storage Permissions: Using
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.