ajthyng
ajthyng

Reputation: 1275

Open File With Intent (Android)

I'd like to open any file (if possible) using an Intent. I have my openFile(Uri file, String mimeType) method defined and it's called using a registered BroadcastReceiver. Here is the method:

private void openFile(Uri file, String mimeType) {
    Intent openFile = new Intent(Intent.ACTION_VIEW);
    openFile.setData(file);
    try {
        context.startActivity(openFile);
    } catch (ActivityNotFoundException e) {
        Log.i(TAG, "Cannot open file.");
    }
}

I'm not currently using mimeType, I'm just trying to get this to work. The result of that openFile method when called on a .pdf that has a Uri of content://downloads/all_downloads/3980 is just a blank pdf opened in the pdf viewer (mime type is probably interpreted correctly) with the 3980 downloadID shown as the filename.

No PDF Displayed

I know what's happening, in that the content Uri is not being resolved properly for whatever reason. I get the Uri with the line Uri localUri = downloadManager.getUriForDownloadedFile(downloadId); where downloadId is the long returned from downloadManager.enqueue(request);

How do I open a file when I have a content type Uri?

Upvotes: 2

Views: 4567

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007524

Call addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION). Otherwise, the other app will not have rights to work with the content identified by that Uri.

Note that this only works if you have rights to work with the content identified by that Uri.

Upvotes: 8

Related Questions