0
votes

i am working on a function to open a pdf document in the download folder of Android storage when the button is clicked. This code runs fine when I select the pdf reader application, but when I run it on some pdf-opening applications (such as WPS Office and Adobe Acrobat) it doesn't open the file immediately, it just opens the application, it doesn't open the intended file immediately. is there something wrong with my code?

I use Intent.ACTION_VIEW, this is the code I wrote:

public void viewPdf() {
    File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
    Uri uri = Uri.fromFile(outputFile);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setType("application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    startActivity(intent);
 }
1
Dont use Uri.fromFile(). Use a FileProvider to serve your file. Needed since Android 7/N.blackapps
Thanks for answering, I have replaced with the provider file. but still for some pdf viewer applications it only opens the pdf viewer application, it doesn't open the pdf file directlyZin_
Any reason you did not post your new code? You dont need help anymore?blackapps

1 Answers

0
votes

Instead of

startActivity(intent);

try

startActivity(Intent.createChooser(intent, "View PDF"));

Also, you don't need

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); at all, which you are setting twice in your example