如何访问下载接收器中的本地文件名?

How to get access to local file name in download receiver?

我正在尝试获取下载文件的文件路径,我提供了有效的接收器,但我如何才能获取文件 name/path?

onReceive 内部

String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

    DownloadManager.Query q = new DownloadManager.Query();
    Cursor c = this.query(q); // how to get access to this since there is no instance of DownloadManager

    try {
        String filePath = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
        Log.i("DOWNLOAD LISTENER", filePath);

    } catch(Exception e) {

    } finally {
        c.close();
    }

}

Cannot resolve method query(...)

您可以通过 ContextgetSystemService() 方法获取 DownloadManager 实例。

像这样的东西应该可以工作:

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

        // get the DownloadManager instance
        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        DownloadManager.Query q = new DownloadManager.Query();
        Cursor c = manager.query(q);

        if(c.moveToFirst()) {
            do {
                String name = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                Log.i("DOWNLOAD LISTENER", "file name: " + name);
            } while (c.moveToNext());
        } else {
            Log.i("DOWNLOAD LISTENER", "empty cursor :(");
        }

        c.close();
    }
}