Android pdf opening not working

I have been trying to get this job for some time. I saw other questions here on how to open PDF files from Android, and the general consensus is the code that I have below. Did I miss 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 an ActivityNotFoundException and shows a Toast.

Exception Message:

 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 installed the pdf application (Aldiko), and I used other applications to run PDF files in Aldiko.

+4
source share
2 answers

Your URI is built appropriately to access the raw resource by ID, but this does not mean that all PDF readers will decide the intent using the android.resource:// URI scheme. It depends on the implementation of the PDF Reader application installed on the user device, but many people check more than just the mimeType installed in your intentions. For example, Adobe Reader will allow for any purpose with a URI file:// URI, content:// URI or no URI at all (only mimeType), but it will not be allowed for a URI that points directly to a resource.

To be as universal as possible, you must first copy any PDF file that you want to read from your resources / resources to the file system (internal or external storage, it does not matter as long as the file is created externally readable). Then pass the intent with the URI to the file instance, and you should have much better luck overall.

A quick test showed that Aldiko ONLY responds to intent with file:// URI and "application / pdf" mimeType, and not one of the other parameters that even Adobe Reader did not allow ... so there is your winner.

NTN

+2
source

Try querying the package 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 if he finds anything to run the PDF files.

The URI looks great, but you can always catch a FileNotFoundException that will be thrown if it cannot find the pdf, and replace your package name with getPackageName() if you are missing a character.

+1
source

Source: https://habr.com/ru/post/1380265/


All Articles