首先分三部分:
xml中配置需要共享的路径;manifest中配置这个fileprovider;代码中调用。 当然,对于项目中存在多个共享路径,就需要对fileprovider进行特殊处理
xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="beta_external_path" path="Download/"/>
/>
</paths>
<files-path/>代表的根目录: Context.getFilesDir()
<external-path/>代表的根目录: Environment.getExternalStorageDirectory()
<cache-path/>代表的根目录: getCacheDir()
manifest:
<provider
android:name=".MyProvider"
android:authorities="${applicationId}.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
注意,这里的authorities,可以随便起,只要你调用时候写对就行了;对于name,本来应该是android.supportV4.FileProvider,但是由于项目中存在了一个,就不必须再新建一个类,继承FileProvider。
代码调用;
File imagePath = new File( Environment.getExternalStorageDirectory(), "Download");
File newFile = new File(imagePath, "test.png");
Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "com.yosemite.testconstarinlayout.fileProvider", newFile);
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(contentUri,"image/*");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(intent);