有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

内部接收

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) 个答案

  1. # 1 楼答案

    您可以通过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();
        }
    }