用Android7.0測試拍照的時候,出現異常android.os.FileUriExposedException: file:///storage/emulated.. exposed beyond app through Intent.getData()
是因為從Android N開始,要在應用間共享文件,需要發送一項 content://URI,并授予 URI 臨時訪問權限。
Android提供FileProvider來簡單實現
實現方法:
1.在manifest中添加provider
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
<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/mis_provider_paths"/>
</provider>
</application>
</manifest>
2.在res目錄下新建一個xml文件夾,并且新建一個mis_provider_paths的xml文件
Paste_Image.png
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="camera_photos" path="."/>
</paths>
上面代表可以用外部存儲的任意位置
如果只想在picture文件夾下讀寫
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="camera_photos" path="picture"/>
</paths>
3.代碼中調用相機
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
uri = Uri.fromFile(file);
} else {
uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".provider", file);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, code);