安卓下载管理器获取文件名

在我的应用程序中,您可以下载一些文件。我使用Android类进行下载。下载完成后,它应该向我显示文件已下载的消息。问题是,可能同时有2,3或4个下载。我的代码如下所示:DownloadManagerBroadcastReceiver

receiver_complete = new BroadcastReceiver(){
         @Override
          public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
                if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE) ){
                    Toast.makeText(MainActivity.this, MainActivity.this.getString(R.string.download_finished, "Here should be the name", Toast.LENGTH_SHORT).show();
                }
         }
     };

如何获取已完成下载的当前文件名?

谢谢。


答案 1

我想你想把这样的东西放在你的街区里。替换为您的 DownloadManager 实例。ifYOUR_DM

Bundle extras = intent.getExtras();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
Cursor c = YOUR_DM.query(q);

if (c.moveToFirst()) {
    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
    if (status == DownloadManager.STATUS_SUCCESSFUL) {
        // process download
        title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
        // get other required data by changing the constant passed to getColumnIndex
    }
}

答案 2

伊恩·香农(Ian Shannon)的回答完全正确,但我要求改进一下:

  • 请记住在使用它后关闭它,避免“光标泄漏”。这会消耗大量资源,必须尽快释放。CursorCursor

  • 如果您为下载添加了一些标题,例如:

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setTitle("Some title");
    

    将给出的值将代替文件名。所以我会推荐这个:DownloadManager.COLUMN_TITLE"Some title"

    String filePath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
    title = filePath.substring( filePath.lastIndexOf('/')+1, filePath.length() );
    

    返回整个路径 (),但使用此代码,我们只能获取文件名。COLUMN_LOCAL_FILENAME/storage/sdcard0/Android/data/.../filename.ext

最终代码:

Bundle extras = intent.getExtras();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(extras.getLong(DownloadManager.EXTRA_DOWNLOAD_ID));
Cursor c = YOUR_DM.query(q);

if (c.moveToFirst()) {
    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
    if (status == DownloadManager.STATUS_SUCCESSFUL) {
        String filePath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
        filename = filePath.substring( filePath.lastIndexOf('/')+1, filePath.length() );
    }
}
c.close();

编辑:将YOUR_DM替换为您的 DownloadManager 实例。


推荐