35

我正在从我的应用程序中删除一个图像文件。我在做

new  File(filename).delete ();

这实际上是在删除文件。但图像在画廊中仍然可见。

在搜索中我发现我们应该使用

getContentResolver().delete(Uri.fromFile(file), null,null);删除

但在这里我得到了例外:

未知的文件 URL。java.lang.IllegalArgumentException:未知的 URL 文件:///mnt/sdcard/DCIM/Camera/IMG_20120523_122612.jpg

当我用任何文件浏览器看到时,都会出现这个特定的图像。请帮我解决这个问题。当图像被物理删除时,有没有其他方法可以更新画廊

4

10 回答 10

36

使用下面的代码,它可能会对您有所帮助。

File fdelete = new File(file_dj_path);
if (fdelete.exists()) {
    if (fdelete.delete()) {
        System.out.println("file Deleted :" + file_dj_path);
    } else {
        System.out.println("file not Deleted :" + file_dj_path);
    }
}

删除图像后刷新画廊使用下面的代码发送广播

(对于 < KITKAT API 14)

 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
 Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

对于 >= KITKAT API 14,请使用以下代码

MediaScannerConnection.scanFile(this, new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
            /*
             *   (non-Javadoc)
             * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
             */
            public void onScanCompleted(String path, Uri uri) 
              {
                  Log.i("ExternalStorage", "Scanned " + path + ":");
                  Log.i("ExternalStorage", "-> uri=" + uri);
              }
            });

因为:

ACTION_MEDIA_MOUNTED

在 KITKAT(API 14) 中已弃用。


2015 年 4 月 9 日编辑

它的工作正常检查下面的代码

public void deleteImage() {
        String file_dj_path = Environment.getExternalStorageDirectory() + "/ECP_Screenshots/abc.jpg";
        File fdelete = new File(file_dj_path);
        if (fdelete.exists()) {
            if (fdelete.delete()) {
                Log.e("-->", "file Deleted :" + file_dj_path);
                callBroadCast();
            } else {
                Log.e("-->", "file not Deleted :" + file_dj_path);
            }
        }
    }

    public void callBroadCast() {
        if (Build.VERSION.SDK_INT >= 14) {
            Log.e("-->", " >= 14");
            MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                /*
                 *   (non-Javadoc)
                 * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
                 */
                public void onScanCompleted(String path, Uri uri) {
                    Log.e("ExternalStorage", "Scanned " + path + ":");
                    Log.e("ExternalStorage", "-> uri=" + uri);
                }
            });
        } else {
            Log.e("-->", " < 14");
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    }

下面是日志

09-04 14:27:11.085    8290-8290/com.example.sampleforwear E/-->﹕ file Deleted :/storage/emulated/0/ECP_Screenshots/abc.jpg
09-04 14:27:11.085    8290-8290/com.example.sampleforwear E/-->﹕ >= 14
09-04 14:27:11.152    8290-8290/com.example.sampleforwear E/﹕ appName=com.example.sampleforwear, acAppName=/system/bin/surfaceflinger
09-04 14:27:11.152    8290-8290/com.example.sampleforwear E/﹕ 0
09-04 14:27:15.249    8290-8302/com.example.sampleforwear E/ExternalStorage﹕ Scanned /storage/emulated/0:
09-04 14:27:15.249    8290-8302/com.example.sampleforwear E/ExternalStorage﹕ -> uri=content://media/external/file/2416
于 2012-05-23T09:08:12.533 回答
35

我看过很多建议使用的答案

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

这可行,但会导致媒体扫描仪重新扫描设备上的媒体。更有效的方法是通过 Media Store 内容提供程序查询/删除:

// 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[] { file.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);
} else {
    // File not found in media store DB
}
c.close();
于 2013-12-26T06:51:23.783 回答
24
File file = new File(photoUri);
file.delete();

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

此代码适用于我,我认为它比重新安装整个 SD 卡更好Intent.ACTION_MEDIA_MOUNTED

于 2014-09-23T09:36:16.850 回答
18

要删除图像,

ContentResolver contentResolver = getContentResolver();
contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            MediaStore.Images.ImageColumns.DATA + "=?" , new String[]{ imagePath });
于 2015-05-22T17:45:25.667 回答
5

我尝试了所有这些解决方案,但在 Android 6 中没有运气。
最后,我发现这段代码运行良好。

public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
    String canonicalPath;
    try {
        canonicalPath = file.getCanonicalPath();
    } catch (IOException e) {
        canonicalPath = file.getAbsolutePath();
    }
    final Uri uri = MediaStore.Files.getContentUri("external");
    final int result = contentResolver.delete(uri,
            MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
    if (result == 0) {
        final String absolutePath = file.getAbsolutePath();
        if (!absolutePath.equals(canonicalPath)) {
            contentResolver.delete(uri,
                    MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
        }
    }
}

我还在 Android 4.4 和 5.1 中对此进行了测试,它运行良好。

于 2016-03-29T23:31:05.320 回答
4
sendBroadcast(new Intent(
           Intent.ACTION_MEDIA_MOUNTED,
           Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

此代码有效,但资源非常昂贵。它卸载然后安装可能会影响某些应用程序或占用大量系统资源以刷新图库的 SDCard。我仍在寻找最好的替代品,如果我得到一个,我会发布。

于 2012-09-22T13:45:33.823 回答
3

在 Kotlin 中,您可以这样做:

private fun deleteImage(path: String) {
    val fDelete = File(path)
    if (fDelete.exists()) {
        if (fDelete.delete()) {
            MediaScannerConnection.scanFile(this, arrayOf(Environment.getExternalStorageDirectory().toString()), null) { path, uri ->
                Log.d("debug", "DONE")
            }
        } 
    }
}
于 2018-09-06T08:37:17.257 回答
1

我有同样的问题,我尝试了三种不同的方法来删除图像。有时它工作,有时它不是。现在花了太多时间后,我拥有的每种方法都会删除图像。我想说的是:小心处理位图。我正在拍照坚持它,然后在需要时旋转:

public static Bitmap rotatePictureToPortraitMode(String filePath, Bitmap myBitmap) {
try {
    ExifInterface exif = new ExifInterface(filePath);
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
    Log.d("EXIF", "Exif: " + orientation);
    Matrix matrix = new Matrix();
    if (orientation == 6) {
        matrix.postRotate(90);
    } else if (orientation == 3) {
        matrix.postRotate(180);
    } else if (orientation == 8) {
        matrix.postRotate(270);
    }
    myBitmap = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); // rotating bitmap
} catch (Exception e) {

}
return myBitmap;
}

之后我试图删除图像,但正如我之前所说,它不起作用。删除此方法有助于我解决问题。

也许这只是我的问题,但一旦我删除它,它对我有很大帮助,所以我想说小心你如何处理图像。对于我的情况,我使用了前面提到的答案:

File file = new File(photoUri);
file.delete();

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

希望能帮助到你!

于 2018-12-06T17:28:09.187 回答
0
public static boolean deltefolderwithimages(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deltefolderwithimages(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}
于 2019-08-28T07:22:08.387 回答
0

DocumentFile.fromSingleUri(context, uri).delete();

为我工作很棒

于 2020-09-24T09:29:06.393 回答