在Android7.0以上手机中,使用系统分享功能分享到微信,会提示“资源未找到,无法分享状态”,原因是7.0以上不能直接通过Uri.parse获取文件路径,需要通过FileProvider来获取文件uri地址,具体操作步骤是:
1、在AndroidMainfest.xm中定义一个provider
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="app.qianmo.com.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="files"
path="." />
<root-path
name="external_999_root"
path="." /> <!-- 对应SD卡 -->
<external-path
name="dcim"
path="DCIM/" />
<external-path
name="my_images"
path="Pictures" />
<external-path
name="external_files"
path="." />
<external-path
name="files_root"
path="Android/data/xxxx(包名)/files/Pictures" />
</paths>
2、分享时使用FileProvider获取uri
Intent intent = new Intent(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
Uri uri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", file);
intent.putExtra(Intent.EXTRA_STREAM, uri);
getContext().startActivity(intent);
} else {
uri = Uri.parse(file.getAbsolutePath());
intent.putExtra(Intent.EXTRA_STREAM, uri);
getContext().startActivity(Intent.createChooser(intent, null));
}
注意:
分享使用intent时直接使用intent,不要再调用`Intent.createChooser(intent, null)`来创建intent