从抓下载管理意图获取文件路径意图、路径、文件

2023-09-04 09:01:34 作者:个人,宁缺毋滥

由于机器人如果用户下载在浏览器中下载管理一些文件4.2被使用。如果用户点击了下载完成通知的意图是,总是启动。的Andr​​oid 4.2之前的意图曾经有下载的文件的路径,在内容的选择,例如:

Since Android 4.2 if a user downloads some file in the browser the DownloadManager is used. If the user clicks the 'download complete' notification an Intent is and was always launched. Before Android 4.2 the intent used to have the downloaded file's path in the content, such that:

intent.getData()

会返回一个字符串,如文件:///storage/emulated/0/Download/some_file.ext 。然而,由于Android 4.2的下载管理器广播和意图与内容方案,如内容://下载/ all_downloads / 2334

would return a String such as file:///storage/emulated/0/Download/some_file.ext. However, since Android 4.2 the download manager broadcasts and intent with a content scheme, such as content://downloads/all_downloads/2334.

我如何检索一个下载文件的本地文件路径?

How do I retrieve the local file path for a downloaded file?

我已经试过如下:

public static String getRealPathFromURI(Uri contentUri, Activity activity) {
    DownloadManager downloadManager = (DownloadManager) activity.getSystemService(Activity.DOWNLOAD_SERVICE);
    String[] contentParts = contentUri.getEncodedPath().split("/");
    Cursor q = downloadManager.query(new DownloadManager.Query().setFilterById(Integer.parseInt(contentParts[contentParts.length - 1])));
    if (q == null) {
        // Download no longer exists
        return null;
    }
    q.moveToFirst();
    return q.getString(q.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
}

但光标不会返回任何行(所以 q.getCount()== 0 ,并为此在过去返回语句抛出异常)。此外,黑客通过分析来自乌里下载文件ID似乎很奇怪。

But the cursor never returns any rows (so q.getCount() == 0 and therefor the last return statement throws an exception). Also, the hack by parsing the download file id from the Uri seems odd.

更新:我也曾尝试:

input = getActivity().getContentResolver().openInputStream(contentUri);

但这会返回一个错误,说明

权限拒绝:读取com.android.providers.downloads.DownloadProvider URI内容://下载/ all_downloads / 2334从PID = 30950,UID = 10064要求android.permission.ACCESS_ALL_DOWNLOADS,或grantUriPermission()

显然,我无法访问下载(因为我的应用程序并没有主动它们 - 浏览器所做的那样)。通过的ContentProvider

推荐答案

通过内容解析得到它是正确的事情。并不是每一个内容的URL将是一个文件。例如,画廊的应用程序会给你的URI,并转化到网络通话或根据来源的本地文件。

Getting it through the content resolver is the right thing. Not every content url is going to be a file. For example, the Gallery app will give you uri's that translate to a network call or a local file depending on the source.

即使你得到真正的文件路径,你可能无法读取它,因为文件的权限,但你可以幸运的是它在外部存储。 您是否尝试过加入 android.permission.ACCESS_ALL_DOWNLOADS 您的应用程序,如异常提示? 这是行不通的,因为权限是在签名级别:(

Even if you'd get to the real file path, you'll probably unable to read it, due to file permissions, although you can be lucky it it's on external storage. Have you tried adding android.permission.ACCESS_ALL_DOWNLOADS to your app like the exception suggests? That won't work, since the permission is at signature level :(