Retrieve file path from caught DownloadManager intent

只谈情不闲聊 提交于 2019-11-29 03:54:45

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.

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 :(

Here's what worked. First, you can't (and shouldn't want to) get the file path as botteaap correctly pointed out. (Credits to him for setting me on the right path.) Instead you get a temporary permission automatically to access the file content, using:

InputStream input = getContentResolver().openInputStream(intent.getData());

You can read this InputStream like any other in Java. It seems there is no way to get the file name. If you need a file, first write the input stream to a (temporary) file.

The SecurityException is throw when your temporary access was revoked. This happend for me on some files that I tried to read incorrectly before and specifically when the Intent was picked up in my Acticity's onNewIntent.

I just want to add to the answer from @erickok as it took me several hours to figure this out. As stated by @jcesarmobile, you are only guaranteed to be able to get the name and size of the file, not the full path.

You can get the name and size as follows, and then save to a temp file:

String filename = null;
Long filesize = null;
Cursor cursor = null;
try {
    cursor = this.getContentResolver().query(intent.getData(), new String[] {
        OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE}, null, null, null );
    if (cursor != null && cursor.moveToFirst()) {
        filename = cursor.getString(0);
        filesize = cursor.getLong(1);
    }
} finally {
    if (cursor != null)
        cursor.close();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!