如何从Android中的图片库中删除文件?

Nic*_*ama 2 android image delete-file android-contentprovider android-file

我正在制作一个具有允许将图像上传到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());
    }
Run Code Online (Sandbox Code Playgroud)

Ala*_*mri 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();
    }

}
Run Code Online (Sandbox Code Playgroud)