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

倾然丶 夕夏残阳落幕 提交于 2019-12-10 18:20:51

问题


I'm trying to get file path of downloaded file, i provided receiver which works but how can i get file name/path?

Inside 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(...)


回答1:


You could get ahold of a DownloadManager instance via the getSystemService() method of Context.

Something like this should work:

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


来源:https://stackoverflow.com/questions/38848110/how-to-get-access-to-local-file-name-in-download-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!