简体   繁体   中英

Can't open external storage file in Android N using FileProvider

I am having trouble opening file inside external storage with Android N.

File path

file:///storage/emulated/0/Download/SamplePDFFile_5mb.pdf

Initial implementation Perfectly work on Android version lower than 7

File file = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SamplePDFFile_5mb.pdf");
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);

The same implementation doesn't work on 7 with below exception.

android.os.FileUriExposedException

So i found out similar questions and follow this in order to fix new android security feature for app targeting to 24 or higher.

New implementation

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SamplePDFFile_5mb.pdf");
//old way
//Uri uri = Uri.fromFile(file);
//new way
Uri uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", file);

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);

provider_paths.xml

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

AndroidManifest.xml

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

Even after adding required tag in Android Manifest, provider_paths.xml and FileProvider, i am not able to open the file. Opening activity close on itself.no error or messages in logcat.

public void getGROUPSTORAGEPremission(){
    int hasWriteContactsPermission = Splash_activity.this.checkSelfPermission(Manifest.permission_group.STORAGE);
    if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
        Splash_activity.this.requestPermissions(new String[]{  Manifest.permission_group.STORAGE},
                PERMISSION_GROUPSTORAGE);
    } else {
       File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SamplePDFFile_5mb.pdf");
     //old way
     //Uri uri = Uri.fromFile(file);
     //new way
     Uri uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", file);

       Intent intent = new Intent(Intent.ACTION_VIEW);
       intent.setDataAndType(uri, "application/pdf");
       intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
       startActivity(intent);
    }

}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == PERMISSION_GROUPSTORAGE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission Granted
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "SamplePDFFile_5mb.pdf");
     //old way
     //Uri uri = Uri.fromFile(file);
     //new way
      Uri uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", file);

       Intent intent = new Intent(Intent.ACTION_VIEW);
       intent.setDataAndType(uri, "application/pdf");
       intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
       startActivity(intent);
        } else {
            // Permission Denied
            //Toast.makeText(mContext, "PERMISSION_GROUPSTORAGE Denied", Toast.LENGTH_SHORT).show();
        }
    }
 }

After N need to check runtime permission .

Maybe late, but I solved it by adding an temporary permission to the intent, by doing the following:

    Uri path = FileProvider.getUriForFile(MainActivity.this, "com.example.root.somepackage.provider", pdfFile);
    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // GRANT TEMPORARY READ PERMISSION
    pdfIntent.setDataAndType(path, "application/pdf");

    try{
        startActivity(pdfIntent);
    }

This was helpful: Granting Content Provider URI Permissions

This simple solution helps me to solve this kind of problems. Hope it will help you and save your time.

public void open_file(String filename) {
    File path =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File file = new File(path, filename);

    // Get URI and MIME type of file
    Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".fileprovider", file);
    String mime = context.getContentResolver().getType(uri);

    // Open file with user selected app
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, mime);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(intent);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM