如何在Android的相册中删除文件?

3
我正在开发一个应用程序,并加入了上传图片到Web服务器的功能。在捕获的图像上传到服务器后,该图像将从用户设备中删除。我已经成功地上传了图片,并检查了文件管理器,确认该图片已被删除。但是,不知何故,当我打开相册时,它仍然存在,尽管显示“无法加载文件”。但是,当我查看详细信息时,它会显示图像的大小。那么,如何完全从文件管理器和相册中删除已上传的图像?
以下是我的代码:
Public Static Boolean deleteDirectory(File path) {
        // TODO Auto-generated method stub
        if( path.exists() ) {
            File files = path;

                if(files.isDirectory()) {
                    deleteDirectory(files);
                }
                else {
                    files.delete();
                }
            }

        return(path.delete());
    }

可能重复了 android : deleting an image - Dhaval Parmar
2个回答

5

您需要更新(扫描)媒体内容提供程序。我使用此方法同时进行删除和扫描媒体内容,但是您需要进行一些更改。

private void DeleteAndScanFile(final Context context, String path,
        final File fi) {
    String fpath = path.substring(path.lastIndexOf("/") + 1);
    Log.i("fpath", fpath);
    try {
        MediaScannerConnection.scanFile(context, new String[] { Environment
                .getExternalStorageDirectory().toString()
                + "/images/"
                + fpath.toString() }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        if (uri != null) {
                            context.getContentResolver().delete(uri, null,
                                    null);
                        }
                        fi.delete();
                        System.out.println("file Deleted :" + fi.getPath());
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });
    } catch (Exception e) {
        e.printStackTrace();
    }

}

这对我有用,这段代码有助于删除和更新媒体内容提供程序。 - Quick learner

3
请尝试这种方法,这段代码对我有效。
refreshGallery(this, videoPath);

.

public static void refreshGallery(Context context, String path) {
    File file = new File(path);
    if (file.exists() && file.isFile()) {
        file.delete();
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Intent intent= new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        context.sendBroadcast(intent);
    } else {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(file.getAbsolutePath())));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接