I tested this and found that the following works. First you download the file yourself and save it on the device, and then you do this:
File file = new File("/sdcard/download/somepdf.pdf"); PackageManager packageManager = getPackageManager(); Intent testIntent = new Intent(Intent.ACTION_VIEW); testIntent.setType("application/pdf"); List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY); if (list.size() > 0 && file.isFile()) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(file); intent.setDataAndType(uri, "application/pdf"); startActivity(intent);
I tested it on different emulators and on a cyanogenic root phone, as well as on HTC Magic. If PDF rendering is not available, the list will return zero and nothing will happen.
It seems important to set the data type to the PDF mime type in order to get the correct behavior.
If you, for example, install droidreader, it will respond to the intention and display pdf.
Of course, you can check before downloading the PDF, and depending on your use case, either do something like pop-up warnings or redirect other intentions to download or something else.
Edit: I have since edited this in a separate method.
public static final String MIME_TYPE_PDF = "application/pdf"; public static boolean canDisplayPdf(Context context) { PackageManager packageManager = context.getPackageManager(); Intent testIntent = new Intent(Intent.ACTION_VIEW); testIntent.setType(MIME_TYPE_PDF); if (packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0) { return true; } else { return false; } }
Manfred Moser May 7, '10 at 17:21 2010-05-07 17:21
source share