Sharing file in Oreo not working

江枫思渺然 提交于 2020-01-05 07:05:14

问题


I'm trying to share an audio file in Oreo. If the file is in internal storage of the device, it runs fine but if the file is present on the external storage it crashes giving this exception - android.os.FileUriExposedException.

How to solve this problem:

public void shareSong(SongInfoModel songInfoModel){

    Uri uri = Uri.parse("");
    File f = new File(songInfoModel.getData());
    if(Build.VERSION.SDK_INT<=Build.VERSION_CODES.N_MR1) {
          uri = Uri.parse("file://" + f.getAbsolutePath());
    }else {
         uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", f);
    }
    Intent share = new Intent(Intent.ACTION_SEND);
    share.putExtra(Intent.EXTRA_STREAM, uri);
    share.setType("audio/*");
    share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(Intent.createChooser(share, "Share audio File"));

}

Manifest:

 <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>

回答1:


If you have an app that shares files with other apps using a Uri, you may have encountered this error on API 24+.

Step 1

add provider to your manifest file

<manifest ...>
<application ...>
    <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>
</application>

Step 2

Create XML file res/xml/provider_paths.xml

 <?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
</paths>

Step 3

add new code

    File file ; // your code
    Intent install = new Intent(Intent.ACTION_VIEW);
    install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    // Old Approach
    install.setDataAndType(Uri.fromFile(file), mimeType);
    // End Old approach
    // New Approach
    Uri apkURI = FileProvider.getUriForFile(
            context,
            context.getApplicationContext()
                    .getPackageName() + ".provider", file);
    install.setDataAndType(apkURI, mimeType);
    install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    // End New Approach
    context.startActivity(install);


来源:https://stackoverflow.com/questions/51121149/sharing-file-in-oreo-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!