Android文件删除在Gallery中留下空占位符

Pau*_*aul 18 android gallery

我通过以下方式插入图片:

    ContentValues values = new ContentValues();   
    values.put(Images.Media.TITLE, filename);
    values.put(Images.Media.DATE_ADDED, System.currentTimeMillis()); 
    values.put(Images.Media.MIME_TYPE, "image/jpeg");

    Uri uri = this.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
Run Code Online (Sandbox Code Playgroud)

但是当我尝试删除时

    File f = new File(imageURI);
    f.delete();
Run Code Online (Sandbox Code Playgroud)

图片不再存在,但空占位符是.有任何想法吗?

Mar*_*ein 15

Android有各种缓存,可以跟踪媒体文件.

试试这个:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Run Code Online (Sandbox Code Playgroud)

它使MediaScanner服务再次运行,这应该从设备的缓存中删除已删除的图像.

您似乎还需要将此权限添加到AndroidManifest.xml:

<intent-filter>
  <action android:name="android.intent.action.MEDIA_MOUNTED" />
  <data android:scheme="file" /> 
</intent-filter>
Run Code Online (Sandbox Code Playgroud)

  • 似乎没有用于删除文件的MediaScannerConnection.scanFile()等效项.如果你发现了另一种不同的方法,请告诉我,否则我的答案是正确的. (4认同)

whi*_*zle 10

如评论中所述,接受的答案使用了大量内存.虽然MediaScannerConnection没有"deleteFile"方法,但只要在删除文件后将旧文件路径传递给"scanFile"方法即可.媒体扫描仪将重新扫描并删除媒体.

在N5上测试.Android 4.4.

编辑:其他已经声明这不适用于4.2

new AsyncTask<Void, Void, Void>(){
        @Override
        protected Void doInBackground(Void... params) {
            String filePath = recording.file.getAbsolutePath();
            recording.file.delete();
            MediaScannerConnection.scanFile(context,
                    new String[]{filePath}, null, null);
            return null;
        }
    }.execute();
Run Code Online (Sandbox Code Playgroud)


man*_*sha 6

您还可以使用以下方法从图库中删除图像:

getContentResolver().delete(imageUri,null,null);

只需确保在调用insert时'imageUri'是uri返回给你的.