0

currently, I'm trying to open my pdf files with a chooser. The problem I'm currently having is that the file tries to open before the chooser is visible. Only when I go back from the opened file I can see the chooser and choose my favorite application. I tried to modify my code according to several StackOverflow suggestions on how to use the chooser but even tho I tried them they won't work.

Here is my code to open the pdf:

case "PDF":
                            Intent pdfIntent = new Intent();
                            pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                            pdfIntent.setAction(android.content.Intent.ACTION_VIEW);
                            Uri contentPDFUri = FileProvider.getUriForFile(context,
                                    "com.ndlp.socialstudy.provider",
                                    my_clicked_file);
                            pdfIntent.setDataAndType(contentPDFUri,"application/pdf");
                            Intent intentpdfChooser = pdfIntent.createChooser(pdfIntent, "Open With");
                            try {
                                context.startActivity(intentpdfChooser);
                            } catch (ActivityNotFoundException e) {
                                Toast.makeText(context, "Please install a PDF app to view your file!", Toast.LENGTH_LONG).show();
                                // Instruct the user to install a PDF reader here, or something
                            }
Abhishek Bhardwaj
  • 1,164
  • 3
  • 14
  • 39

2 Answers2

1
Intent myIntent = new Intent(Intent.ACTION_VIEW);
        myIntent.setData(Uri.fromFile(file));
        Intent j = Intent.createChooser(myIntent, "Choose an application to open with:");
        startActivity(j);
Muhammad Saad Rafique
  • 3,158
  • 1
  • 13
  • 21
0

Instead of calling

Intent intentpdfChooser = pdfIntent.createChooser(pdfIntent, "Open With");

try

Intent intentpdfChooser = Intent.createChooser(pdfIntent, "Open With");

and let the Android system figure out what are the applicaitons which can handle your pdfIntent

In one of my apps I'm using:

Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri, "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open PDF using");
try {
        mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
        Toast.makeText(mContext, "No Applications found to open pdf", Toast.LENGTH_SHORT).show();
}

and it's working for me.

Amit Barjatya
  • 249
  • 3
  • 14
  • nice suggestion! Does not work for me tho it still tries to open and only if I back out of it I get directed to the file chooser:/ – Patrick Nadler Oct 27 '17 at 10:21