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

Java 如何在下载接收器中访问本地文件名?,java,android,broadcastreceiver,Java,Android,Broadcastreceiver,我正在尝试获取下载文件的文件路径,我提供了接收器,该接收器可以工作,但如何获取文件名/路径 内部接收 String action = intent.getAction(); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { DownloadManager.Query q = new DownloadManager.Query(); Cursor c = this.query(q); // how to

我正在尝试获取下载文件的文件路径,我提供了接收器,该接收器可以工作,但如何获取文件名/路径

内部接收

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();
    }

}
无法解析方法查询(…)


您可以通过
Context
getSystemService()
方法获得
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();
    }
}