'How to save files to shared storage in Scoped storage?

I wanna save files to shared storage in scoped storage (in /storage/emulated/0/Download/), but As you know Environment.getExternalStorageDirectory() to access the root of external storage is deprecated in android 11 or higher (because Scoped storage is mandatory for all apps targeting Android 11). Could you tell me a way to save and retrieve files to shared storage in scoped storage?



Solution 1:[1]

OutputStream outputStream;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName); // file name required to contain extestion file mime
            values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS+"/DIRECTORY_NAME"); //DIRECTORY 
            Uri extVolumeUri = MediaStore.Files.getContentUri("external");
            Uri fileUri = context.getContentResolver().insert(extVolumeUri, values);
            outputStream = context.getContentResolver().openOutputStream(fileUri);
        }
        else {
            File root = new File(Environment.getExternalStorageDirectory()+File.separator+"DIRECTORY_NAME", "images");
            File file = new File(root, fileName );
            Log.d(TAG, "saveFile: file path - " + file.getAbsolutePath());
            outputStream = new FileOutputStream(file);
        }
        byte[] bytes = bodyData.getBytes();
        outputStream.write(bytes);
        outputStream.close();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jayaraju Medisetti