ActivityNotFoundException is not triggered to open a downloaded PDF file - android

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.

Related

Android app opening browser in the same tab?

I'm finding this hard to explain, but i'll do my best.
I have an app that opens the browser (firefox) and send information from that app to the webpage as a php variable, the problem i have is that i am doing this quite a lot, and everytime it opens the browser its opening a new tab.
I know there is no way to close a tab using javascript etc, so is there a way to ensure it always opens into the same current tab so i dont end up with several open at once.
I dont want to keep having to close firefox tabs whenever the app fires up the browser.
Sorry if its hard to make sense of.
Thanks.
Probably this is a bit late, but I have managed to accomplish what you want only using Chrome app.
String url = "http://www.mypage.com";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.putExtra(Browser.EXTRA_APPLICATION_ID, "com.android.chrome");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
This allows you to re-use the current opened tab on Chrome and change the current URL in that tab to the one you are providing in the intent.
I also have tried with no success on Firefox.
I hope this helps.
For Firefox android app to replace the existing url of current tab.
String package = "org.mozilla.firefox";
String url = "http://www.test.com";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setPackage(package);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, package);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
For chrome or other browsers, just change the package name. Hopefully it will solve the problem.
Answer used to open a "sample.html" file in same tab instead of creating a new tab of Google Chrome browser.
btnClickMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(Environment.getExternalStorageDirectory(), "sample.html");
Uri uri2 = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW, uri2);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.android.chrome", "com.google.android.apps.chrome.Main");
intent.putExtra(Browser.EXTRA_APPLICATION_ID, "com.android.chrome");
try {
startActivity(intent);
} catch (Exception e) {
Log.e("Exception ", e.getLocalizedMessage());
}
}
});
Note : Kindly check your Storage permission before proceeding.

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.

Android - Open a file with specific app using intent

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.

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);

Displaying PDF in a view in Android

In Android I need to display a PDF file, which is in the asset folder, in a view. Can anyone help me out with the sample code?
I don't think its possible to display it in a view. You will have to make an Intent and then call an external program to do so.
File sd = new File("example.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(sd));
intent.setDataAndType(Uri.fromFile(sd), "application/pdf");
try {
getContext().startActivity(intent);
} catch(ActivityNotFoundException e){
// Show a message that a PDF viewer is not installed
Toast.makeText("No PDF reader available",Toast.LENGTH_LONG).show();
}

Categories

Resources