Can we delete an image file using MediaStore API? if yes then how
Asked Answered
N

2

6

I have a requirement to delete screenshot image file after a certain time using background service in my app and it was working fine using the above method

private void deleteTheFile(String path) {
    File fdelete = new File(path);
    if (fdelete.exists()) {
        if (fdelete.delete()) {
            getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(path))));
            Log.i(TAG, "deleteTheFile: file deleted");
        } else {
            Log.i(TAG, "deleteTheFile: file not dellleeettteeeddd");
        }
    }

But as everyone knows about the changes which came with android R (11) So I tried to update my app with

MANAGE_EXTERNAL_STORAGE permission

But Google rejected my update saying

Issue: Need to use Media Store API

You have requested access to All Files Access permission but it appears that your app's core feature requires access to only Media Files. With the MediaStore API, apps can contribute and access media that's available on an external storage volume without the need for the access all files permission.

Please update your app so that the feature uses Media Store APIs and remove All Files Access (MANAGE_EXTERNAL_STORAGE) permission.

But I have never worked with media store API before and I don't know can it delete an image file with it, because deleting a file comes under writeable section

Noreennorene answered 2/6, 2021 at 2:37 Comment(0)
O
3

Using createDeleteRequest

private fun deleteImages(uris: List<Uri>) {
  val pendingIntent = MediaStore.createDeleteRequest(contentResolver, uris.filter {
    checkUriPermission(it, Binder.getCallingPid(), Binder.getCallingUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != PackageManager.PERMISSION_GRANTED
  })
  startIntentSenderForResult(pendingIntent.intentSender, REQ_CODE, null, 0, 0, 0)
}

using contentResolver

// Remove a specific media item.
val resolver = applicationContext.contentResolver

// URI of the image to remove.
val imageUri = "..."

// WHERE clause.
val selection = "..."
val selectionArgs = "..."

// Perform the actual removal.
val numImagesRemoved = resolver.delete(
        imageUri,
        selection,
        selectionArgs)

https://github.com/android/storage-samples/tree/main/MediaStore

This is an android official sample you can follow to have an understanding and try to implement it using MediaStoreAPI

Okay answered 2/6, 2021 at 2:55 Comment(6)
Thank you i will try them and update the result, do I have also to use any permissions for them?Noreennorene
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />Okay
sorry but what do you mean by maxSdkVersion 28, will it not working on sdk 29 and 30?Noreennorene
no for deleting a file you need write access till API 28 only that is the reason to use the maxSdkVersion else on API below 29 you will get a permission issue errorOkay
so you mean if i set the max sdk 28, my app will still be able to delete files in sdk 29 and 30Noreennorene
@TehleelMir Is google approved after you changed to MediaStore API?Java
S
1
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
    val pendingIntent = MediaStore.createDeleteRequest(context.contentResolver, getImageDeleteUri(context, filePath))
    context.startIntentSenderForResult(pendingIntent.intentSender, requestCode, null, 0, 0, 0)}

//finally handle it's result in onActivityResult

getting delete uri from image path:

fun getImageDeleteUri(context: Context, path: String): Uri? {
    val cursor = context.contentResolver.query(
      MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      arrayOf(MediaStore.Images.Media._ID),
      MediaStore.Images.Media.DATA + " = ?",
      arrayOf(path),
      null
    )
    val uri = if (cursor != null && cursor.moveToFirst())
    ContentUris.withAppendedId(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID))
    ) else null
    cursor?.close()
    return uri

}

Stela answered 21/10, 2022 at 7:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.