Lucas Barrionuevo
Lucas Barrionuevo

Reputation: 11

Read a PDF on Android 10

Need to read a PDF on Android 10 The following code works fine on Android 9.0 but on Android 10 the application responsable for show the PDF just blink and return to my application.

            File pdfFile = new File(getExternalFilesDir(null), "Pdf");
            pdfFile.setReadable(true);
            if (pdfFile.exists()) {
                if (pdfFile.canRead()) {
                    if (pdfFile.canWrite()) {
                        Uri path = Uri.fromFile(pdfFile);
                        Intent objIntent = new Intent(Intent.ACTION_VIEW);
                        objIntent.setDataAndType(path, "application/pdf");
                        objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                        startActivityForResult(objIntent, req_code);
                    }else{
                        Toast.makeText(MainActivity.this, "Not writable! ", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(MainActivity.this, "Not readable! ", Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(MainActivity.this, "The file does not exists! ", Toast.LENGTH_SHORT).show();
            }

On the method onActivityResult I'm receiving RESULT_CANCELED as result_code and data == null.

Upvotes: 1

Views: 1252

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006839

The following code works fine on Android 9.0

Somebody on your project did something unfortunate to allow that code to work on Android 9. It should have failed three years ago, starting with Android 7.0, with a FileUriExposedException.

On Android 10, apps do not have access to external storage, except for a few limited app-specific locations. This is what Google was warning about starting with Android 7.0, that you should not use Uri.fromFile() anymore.

The right solution three years ago — and the right solution today — is to use FileProvider to make that PDF available to the PDF viewer app.

See also:

Upvotes: 1

Related Questions