Android 10: How to delete MediaStore item and it's associated data on file system programmatically?

时光怂恿深爱的人放手 提交于 2020-04-16 02:59:04

问题


I am updating my app to use Scoped Storage feature introduced in Android 10.

My app works with MediaStore and displays images, videos and audio files and provides ability for user to delete item.

What I did earlier to delete file:

  1. Got path from MediaStore.MediaColumns.DATA
  2. Used new File(path).delete() to delete that file
  3. Manually updating MediaStore

Now that MediaStore.MediaColumns.DATA is not available I migrated to deleting items from MediaStore using ContentResolver.delete()

For example I have uri of the item: content://media/external/images/media/502 (its valid uri, I display it's thumbnail in grid). It doesnt matter whether I inserted this item in MediaStore or some other app did.

I use context.getContentResolver().delete(uri, null, null). It either succeeds in deletion (returns 1 row) or catching RecoverableSecurityException to use startIntentSenderForResult() to get access to current uri and then using the same getContentResolver().delete() to delete it in onActivityResult() and then getting successful deletion.

Either way that item is removed from MediaStore and is neither showing in result when I query MediaStore for images, nor in other applications.

BUT this file exists on file system (checked using SAF and various file managers (Google Files, Total Commander))

Sometimes (depends on Android version and media type) these items are brought back to MediaStore after phone reboot (or after opening Google Photos - it scans file system)

For example: Android 10 on my Google Pixel and Google Pixel 3a XL behaves as described above for Images/Video/Audio, but Android 9 on Xiaomi Mi A2 Lite behaves like this only with Audio files, while deleting Images/Video fine.

I have android:requestLegacyExternalStorage="false" in manifest.

Is there a way to force MediaStore to delete data on file system as well? Why is file on file system left behind?


回答1:


According to my observations there is no force delete.

I usually add several checks if a file has really been deleted on Android Q it is also not possible to delete an entire album without the user manually confirming each file. this makes deleting files on the device uninteresting for me



来源:https://stackoverflow.com/questions/60702967/android-10-how-to-delete-mediastore-item-and-its-associated-data-on-file-syste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!