Tom Fobear Tom Fobear - 1 month ago 7
Android Question

Android: Open saved file in default app from my app

First off, sorry if this has been asked but I cannot find it. I am downloading documents in my app from a remote resource. Once the document is downloaded, I want to open it for the user. What I want to know is how do I check if they have an application to handle Pdf or Tiff and launch it in the default application for them?

Thank you.

edit

here is part of the solution:

Intent viewDoc = new Intent(Intent.ACTION_VIEW);
viewDoc.setDataAndType(
Uri.fromFile(getFileStreamPath("test.pdf")),
"application/pdf");

PackageManager pm = getPackageManager();
List<ResolveInfo> apps =
pm.queryIntentActivities(viewDoc, PackageManager.MATCH_DEFAULT_ONLY);

if (apps.size() > 0)
startActivity(viewDoc);

Answer

Step #1: Create an ACTION_VIEW Intent, using setDataAndType() to provide a Uri to your downloaded file (e.g., Uri.fromFile()) and the MIME type of the content (e.g., application/pdf).

From there, you have two options:

Step #2a: Use PackageManager and queryIntentActivities() with that Intent. If it returns a zero-length list, you know there are no candidates, and therefore can disable any buttons, menu choices, or whatever that would lead to calling startActivity() on that Intent.

or

Step #2b: Just call startActivity() when the user wants to view it, and catch the exception that occurs when there are no supported apps installed. This is simpler than #2a above, but not quite as user-friendly.