Reputation: 10329
I've been trying to get this working for some time now. I've seen the other questions here about how to open pdfs from Android, and the general consensus is the code that I have below. Am I missing something?
try
{
Uri path = Uri.parse("android.resource://com.TeamGLaDOS.DayTradeSim/" + R.raw.teamdoc);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
this.startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(this, "No Application Available to view PDF", Toast.LENGTH_SHORT).show();
}
Edit: It always throws the ActivityNotFoundException and shows the Toast.
The exception message is this:
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=android.resource://com.TeamGLaDOS.DayTradeSim/2130968576 typ=application/pdf }
Edit 2: I have a pdf application installed (Aldiko) and I've used other apps to launch pdfs in Aldiko before.
Upvotes: 5
Views: 3655
Reputation: 63293
Your URI is constructed appropriately to access a raw resource by ID, but that doesn't mean that all PDF readers will resolve an intent with an android.resource://
data URI scheme.
It depends somewhat on the implementation of the PDF Reader application installed on the user's device, but many check more than just the mimeType set in your intent. Adobe Reader, for example, will resolve for any Intent with a file://
URI, content://
URI, or no URI at all (just the mimeType), but it will not resolve for a URI pointing directly at a resource.
To be as universal as possible, you should first copy any PDF file you want to read out of your assets/resources and onto the file system (internal or external storage, makes no difference as long as the file is created externally readable). Then pass the intent with a URI to the file instance, and you should have much better luck overall.
A quick test showed that Aldiko ONLY responds to an Intent with a file://
URI and "application/pdf" mimeType, and none of the other options that even Adobe Reader resolved to...so there's your winner.
HTH
Upvotes: 2
Reputation: 3440
Try querying the packet manager:
PackageManager packageManager = getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/pdf");
List list = packageManager.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
intent.setDataAndType(path, "application/pdf");
startActivity(intent);
}
This will check to see if it finds anything to run pdfs with.
The URI looks fine but you can always catch FileNotFoundException
which would be thrown if it can't find the pdf, and replace your package name with getPackageName()
in case you're missing a character.
Upvotes: 1