Java – How do I access the local file name in the download receiver?

How do I access the local file name in the download receiver?… here is a solution to the problem.

How do I access the local file name in the download receiver?

I’m trying to get the file path

to the downloaded file, I provided a valid sink, but how do I get the filename/path?

onReceive internally

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(…)

Solution

You can get the DownloadManager instance through the getSystemService() method of the 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();
    }
}

Related Problems and Solutions