Android - Open a file with specific app using intent - android

How can I open a .pdf file with a specific app like adobe reader using an intent?
Something like:
Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
intent.setData(Uri.fromFile(file)); //? - set file to open
startActivity(intent);
I don't want to select an app from a list, the intent must open the file using the specified app.

If you want to open other application then you have to give package name.
Check below code.
try {
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(Uri.fromFile(file), "application/pdf");
mIntent.setPackage("com.adobe.reader");
startActivity(Intent.createChooser(mIntent, "View PDF"));
} catch (Exception e) {
//App not found
e.printStackTrace();
}
If you want to open anyother PDF Viewer app then just change PackageName Instead of "com.adobe.reader"

You can use this answer on another thread. It is for ACTION_SEND, but you can adapt it for ACTION_VIEW in your case.

Related

Android open PDF from URI starting content

I am trying to open up PDF using intent that takes the following:
Here is the code that I have:
Intent intent = new Intent(Intent.ActionVIEW)
intent.setDataAndType(Uri.parse("CONTENTURI + FILENAME","application/pdf"
try { startActivity(intent)} catch excpetion and so on.
It pops up with whatever applications I have installed, from Adobe Reader, Google PDF reader, POLARIS(as I am using Galaxy Tab 3 for testing), and none of those work. Each say unsupported document.
Does download and show the right solution in this case, or any ideas? Thanks in advance!
Following code triggers the VIEW action for pdf files (open the default PDF viewer, choose between applications capable to view PDFs or get an error if you don't have any installed).
File file = new File("your pdf path here");
if (file.exists()) {
Uri pdfPath = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(pdfPath, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
//if user doesn't have pdf reader instructing to download a pdf reader
}
}
NOTE: The PDF should not be saved local to application, or else the third party app won't have access. You should use media location.

ActivityNotFoundException is not triggered to open a downloaded PDF file

I want to download a PDF from a url and also want to trigger catch phrase if no PDF Viewer is detected.
Here's my code:
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(materialPdfUrl)));
} catch (ActivityNotFoundException e) {
openDialog(getString(R.string.error),
getString(R.string.no_pdf_reader));
}
Now the problem is that ActivityNotFoundException is never triggered because it always download the PDF even if there is no PDF Viewer around. How do you suggest I do this?
EDIT:
Here's my old code:
Intent pdfIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(materialPdfUrl));
pdfIntent.setType("application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(pdfIntent);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(materialPdfUrl)));
is starting an Implicit Intent and therefore will not throw ActivityNotFoundException.
If you read this http://developer.android.com/guide/components/intents-filters.html#ccases
Consider, for example, what the browser application does when the user follows a link on a web page. It first tries to display the data (as it could if the link was to an HTML page). If it can't display the data, it puts together an implicit intent with the scheme and data type and tries to start an activity that can do the job. If there are no takers, it asks the download manager to download the data. That puts it under the control of a content provider, so a potentially larger pool of activities (those with filters that just name a data type) can respond.
Therefore if no PDF viewers are found the Android Download Manager will attempt to download the file (rather than throw that exception).
If you want to view the pdf or be told you cannot view it (rather than download) then you will need to query the system manually using the PackageManager to find out if an application will respond to your intent rather than just firing and forgetting.
FYI ActivityNotFoundException will be thrown for Explicit Intent's something like:
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.facebook","NewsFeedActivity.java"));
startActivity(intent);```
I would recommend using the PackageManager to detect if the system will handle a PDF intent for you.
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW)
.setType("application/pdf");
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY;
if (list.size() > 0) {
// Happy days a PDF reader exists
startActivity(intent);
} else {
// No PDF reader, ask the user to download one first
// or just open it in their browser like this
intent = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("http://docs.google.com/gview?embedded=true&url=" + pdfUrl);
startActivity(intent);
}
See this blog post for more info on checking intents. The added benefit of this approach is that you can grey out/remove menu options before the app even tries to execute the Intent. Then you can explain to the user in a slightly more friendly way that they need to grab a PDF viewer app, or indeed apply some logic to fallback to a web based PDF viewer.
Having trialled this approach with Foxit Reader and Adobe Reader they both seem to have different behaviours. Foxit will not download the PDF for you, it will redirect you to the browser and download the file. Adobe will download the file for you then display it.
So to get round this difference once you have detected that a PDF viewer is available then you will probably want to download the PDF to the SD card, for example the downloads folder. This is probably best achieved in an AsyncTask, or you might be able to use the DownloadManager. Then open the local file Uri in the preferred reader. This should get round the difference in behaviour. Maybe open a ticket with Foxit to bring it into line with Adobe? ;)
The function startActivity() you use is not on the condition that the PDF reader is not exist, it only download the PDF from the URL, and if there are PDF Readers then it will offer a selector, just as the function of clicking on a PDF file.
you may try this code. This may helpful to you.
Intent intent = new Intent();
intent.setClassName("com.adobe.reader", "com.adobe.reader.AdobeReader");
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (Exception e) {
AlertDialog.Builder builder = new AlertDialog.Builder(
getApplicationContext());
builder.setTitle("No Application Found");
builder.setMessage("Download application from Android Market?");
builder.setPositiveButton(
"Yes, Please",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
Intent marketIntent = new Intent(
Intent.ACTION_VIEW);
marketIntent.setData(Uri
.parse("market://details?id=com.adobe.reader"));
mProgressDialog.dismiss();
startActivity(marketIntent);
}
});
builder.setNegativeButton("No, Thanks",
null);
builder.create().show();
}
That is because your device or emulator does not have an application capable of viewing a local PDF file.
Whenever you start an intent, you should have the native app installed on the emulator to handle that intent. Ex. If you invoke an intent with Maps as the action, you would have to use the Google API's based emulator. By default, android emulator does not have a PDF reader. You could test this on a device with a PDF reader and it should work fine.
use startActivityForResult(..).
See the link here.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
startActivityForResult(intent, REQUEST_CODE);
You will get the result in onActivityResult(..) of your activity.

PDF rendering in android

I am newbie to android and development world. I need help to solve this problem.(scenario as follows)
I have created one android app using HTML5 and CSS and bundle it out using phonegap.
Now I need to display PDF file in this app with two options for user whether first download and then read or second read online
So My problem is, I am not able to dispaly PDF in app.
How could I achieve this? please help . I am trying to solve it from last 4 days and tried out each and solution which is already given in forum , but still no success.
It would be great for me if someone ans step by step procedure or one example to refer.
Thank You
Minal
This may help: How to open a PDF via Intent from SD card
The basic idea is to get a pdf app to render the pdf for you, and your app just kicks off an intent to do that.
try this code
private void openBook() {
File file = new File(mRealPath);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, getString(R.string.application_type));
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(FirstTab.this,
getString(R.string.no_application_found),
Toast.LENGTH_SHORT).show();
}
}
you can open pdf file via intent like this
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),”application/pdf”);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

Setting default browser for activity programmatically

I'm developing an android app and among other functionality I need to open some urls in external web browser. Can I programmatically set a default application for that, so the user won't be able to choose from the list of available browsers? I mean, I want to set default browser only for my app but not for the whole operating system.
Yes, for this you can force your application to always open native android browser only. For this you have to identify the launching Activity of Browser application, something like this:
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.google.android.browser","com.google.android.browser.BrowserActivity"));
intent.setAction("android.intent.action.VIEW");
intent.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse(url);
intent.setData(uri);
try
{
startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
}
You can use .setPackage for the intent: http://developer.android.com/reference/android/content/Intent.html#setPackage(java.lang.String) . Call it with the browser's package name (defined in its manifest, package attribute).
I'm using something similar for firing up the Google+ application for sharing a string:
Intent shareIntent = ShareCompat.IntentBuilder.from(getActivity())
.setText("Dummy string to share")
.setType("text/plain")
.getIntent()
.setPackage("com.google.android.apps.plus");
startActivity(shareIntent);
In my example, "com.google.android.apps.plus" is the package name for the Google+ application.
Sharedpreference for Browser class is "MODE_private" , so we can't access the home_page changing steps directly programatically,
iff we want to do, we should do through Browser.java opensource code and we should get some idea from there itself.

How to open PDF file in android emulator

I would like to know how to open a PDF file?
What all changes do we need to make in the manifest file.
Can I open it in a browser? What all permissions would be required for it?
If there is an application installed that handles the application/pdf mime type then you can open it. You cannot specify that it only be opened in browser unless browser is the only application that handles it. Following is the code snippet for opening a pdf file
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}

Categories

Resources