Android open/view pdf: intent chooser cannot find any application for opening pdf file stored in 'Google Drive'
Asked Answered
S

0

0

I was trying to create a chooser to grant users freedom to open a pdf file with the application they prefer.

Here's my approach:

    private void openPdf(String pdfUrl, String mime) {
//        Intent pdfViewIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        Intent pdfViewIntent = new Intent(Intent.ACTION_VIEW);
        pdfViewIntent.setDataAndType(Uri.parse(pdfUrl), mime);
        Log.d(TAG, "openPdf: uri: " + Uri.parse((pdfUrl)));

        Intent chooser = Intent.createChooser(pdfViewIntent, "Choose an app");
//        chooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // optional

        startActivity(chooser);
        finish();
    }

The pdf url is something like this: https://drive.google.com/file/d/.../view?usp=sharing

And for the mime type, I tried using both "application/vnd.google-apps.document" and "application/pdf".

Now, when the user clicks on document, I get an output like the following:

my output

But I want an output like the following screenshot: (it appears when I try to open the same link with WhatsApp)

desired output

NOTE 1: using WebView is not a good option for me.

NOTE 2: the above approach works if the URL is in the format https://example.com/.../filename.pdf. But it fails for Google Drive's link.

Snuffer answered 17/1, 2022 at 7:14 Comment(6)
Did you download the PDF in the first place? as I think you can not open PDF directly in a local PDF viewer and if you have downloaded the PDF then your code is missing a flag which is Intent.FLAG_GRANT_READ_URI_PERMISSIONFerocity
was trying to create a chooser to grant users freedom to open a pdf file... That has nothing to do with a chooser but with using an ACTION_VIEW intent.Aladdin
Set type to "text/html".Aladdin
@RakshitNawani I did not download the pdf in my code. However, when the pdf url is in the format https://our.domain.name/relativeurl/filename.pdf the above solution works perfectly. This solution fails only when google drive's url is provided.Snuffer
@Snuffer The last time worked on this we were unable to open Google drive's PDF directly because of a known bug from google drive, we need to download the PDF in the first place and then open the downloaded PDF. I would suggest doing the same if you are unable to move forward.\Ferocity
Google Drive does not create direct links to the files, so when the system opens the URL it gets a webpage, not a PDF. Try using /preview instead of /view at the end of your URL or generate a direct download link for the google drive file of the format https://drive.google.com/uc?export=download&id=DRIVE_FILE_ID where DRIVE_FILE_ID are the letters between /d/ and /view.Porcine

© 2022 - 2024 — McMap. All rights reserved.