android - 无法删除使用 MediaStore 插入的图像

标签 android image mediastore

我正在保存一张用毕加索加载的图像以便稍后共享。这是我用来保存它的代码:

String path = MediaStore.Images.Media.insertImage(
                    mContext.getContentResolver(), mImageBitmap, "Shared image", null);

return Uri.parse(path);

现在,当图像被共享时,我必须使用 URI 删除它。我已经尝试过我在这里看到的一些答案,但没有一个有效。该图像仍然出现在图库中。这些是我用过的方法:


// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };

// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { new File(mImageUri.toString()).getAbsolutePath() };

// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);

if (c.moveToFirst()) 
{
    // We found the ID. Deleting the item via the content provider will also remove the file
    long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
    Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
    contentResolver.delete(deleteUri, null, null);
}

c.close();

File file = new File(mImageUri.toString());
// This returns false
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(mImageUri.toString()))));

知道我做错了什么吗?

谢谢

最佳答案

尝试删除

    String[] retCol = { MediaStore.Audio.Media._ID };

        Cursor cur = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                retCol,
                MediaStore.Images.Media.TITLE + "='"+TEMP_FILE_TITLE+"'", null, null
        );
    try {
        if (cur.getCount() == 0) {
            return;
        }
        cur.moveToFirst();
        int id = cur.getInt(cur.getColumnIndex(MediaStore.MediaColumns._ID));
        Uri uri = ContentUris.withAppendedId(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id
        );
       int cnt = context.getContentResolver().delete(uri, null, null);
}finally {
                cur.close();
            }

在您的情况下,替换 TEMP_FILE_TITLE =“共享图像”

关于android - 无法删除使用 MediaStore 插入的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42828023/

相关文章:

android - 从 Play 商店更新应用程序后出现 DeadObjectException?

java - Android FileNotFound 异常 - 无法从没有文件格式的图像 URL 获取 InputStream

html - 文本与图像垂直居中

Android:在 MediaStore 中查询期间出现磁盘 I/O 错误

PowerVR G6200 上带有 EGLConfigChooser 的 java.lang.RuntimeException

Android ..当我沿着适配器向下滚动时ListView崩溃..

css 图像连续响应

android - 安卓的局限性

Android 光标错误 - "make sure cursor is initialized correctly before accessing data from it..."

android - 我如何从android上的相机获取位图?