Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android select PDF using Intent on API 18

I'm using following codes to select a PDF file using Intent. It perfectly works on Android 5.0+ but no suitable application to open a PDF file message appears on API 18.

public static Intent pickPdf() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    intent.addCategory(Intent.CATEGORY_DEFAULT);
    return intent;
}

startActivityForResult(Intent.createChooser(pickPdf(), "Open with"), PICK_PDF);
like image 698
Alex Avatar asked Oct 31 '22 20:10

Alex


1 Answers

As @CommonsWare suggested -- there is no guarantee that an app, which handles PDFs is installed.

How I've solved this before is by using an App Chooser, like so:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Intent intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // Instruct the user to install a PDF reader here, or something
    ShowToast(TAG, "Unable to open PDF. Please, install a PDF reader app.");
}   
like image 86
Sipty Avatar answered Nov 03 '22 00:11

Sipty