How to create and delete public files using scoped storage, Android Q

358 Views Asked by At

We have an app that sends MMS messages. The Android MmsManager requires a URI parameter that points to a file. It seems this file needs to be public, or the MmsService gets an Io exception for Permission denied. So in conforming with new scoped storage rules I create a .dat file in the MediaStore DownLoads folder. This works fine, even if storing .dat files in the MediaStore doesn't make sense to me. But after the MMS message is sent, I need to delete this file. I can't see any way of doing this without asking the user for permission, or using android.permission.MANAGE_EXTERNAL_STORAGE. Asking the user for permission to delete files he doesn't even know about is obviously not good. And of course android.permission.MANAGE_EXTERNAL_STORAGE requires permission from Google to use, and seems overkill just to be able to remove a data file that was created by the app. So, is there any way to create a public file that can later be deleted. I am already aware of android:requestLegacyExternalStorage="true" which is a very temporary solution, and Environment.getExternalStoragePublicDirectory which is deprecated. The file is created using code similar to below. pdu is a previously created byte array.

final String fileName = "send." + String.valueOf(Math.abs(mRandom.nextLong())) + ".dat";
    ContentResolver contentResolver = mContext.getContentResolver();
    ContentValues contentValues = new ContentValues();

    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
    contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);

    Uri contentUri = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues);

try {
     writer = mContext.getContentResolver().openOutputStream(contentUri);
     writer.write(pdu);
    } catch (final IOException e) {
        Log.e(TAG, "Error writing to output stream in MmsSender. e= ", e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException writing PDU file in MmsSender, e= " + e);
            }
        }
    }
0

There are 0 best solutions below