android 7.0以上獲取文件路徑使用FileProvider

一、先在AndroidManifest.xml文件中添加

<manifest>
	...
	<application>
	...
	<provider
		android:name="androidx.core.content.FileProvider"
		android:authorities="你的包名.fileprovider"
		android:exported="false"
		android:grantUriPermissions="true">
		<meta-data
		    android:name="android.support.FILE_PROVIDER_PATHS"
		    android:resource="@xml/file_paths" /> 
	</provider>
	...
	</application>
</manifest>

二、在res目錄下新建xml/file_paths

//每個節點都支持兩個屬性:name+path
//path:需要臨時授權訪問的路徑(.代表所有路徑) 
//name:就是你給這個訪問路徑起個名字
<?xml version="1.0" encoding="utf-8"?>
<paths  xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="app" path="" />//調用Environment.getExternalStorageDirectory()路徑下的文件
    <files-path name="app" path="" />//調用context.getFilesDir()路徑下的文件
    <cache-path name="app" path="" />//調用context.getCacheDir()路徑下的文件
    <external-cache-path name="app" path="" />//調用context.getExternalCacheDir()路徑下的文件
    <external-files-path name="app" path="" />//調用context.getExternalFilesDir(String)路徑下的文件
</paths>

三、在使用文件路徑的地方做判斷

        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(activity, 	你的包名 + ".fileProvider", file);
        } else {
         
            uri = Uri.fromFile(file);
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章