删除下载的文件 android

Delete a downloaded file android

所以我使用 DownloadManager 使用以下代码从 Internet 下载文件:

public void DownloadFile()
    {
        Log.d("DownloadFileEntered", "true");

        try {
            String url = "https://firebasestorage.googleapis.com/v0/b/roti-bank-testing.appspot.com/o/SocialGallery%2Fsome.jpg?alt=media&token=d2ddd40f-0c04-441c-82b1-585fd8743b19";
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "somegif.gif");
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            long d = manager.enqueue(request);


        }catch (Exception e)
        {
            Log.d("DownloadFileEntered", "Error."+e.toString());
        }
    }

现在说,我要删除这个文件。 为此,我使用了以下代码:

    File file = new File("file://" + Environment.DIRECTORY_DOWNLOADS + "/somegif.gif");
    boolean d = file.delete();
    Log.d("DownloadFileEntered", "D : "+d);

但显然,最后一个Log.d 给出的输出为false,文件也没有被删除。那么,从外部存储中删除文件的正确方法是什么?

另外,下载完成后可以运行一个函数吗?如果是那么怎么办?

希望对您有所帮助:

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/somegif.gif");
    boolean d = file.delete();
    Log.d("DownloadFileEntered", "D : "+d);

并且不要忘记在您的 manifest.xml:

中设置此权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>