1.申请权限:
添加到AndroidManifest.xml。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2.读取文件
string filepath = "/**.mp4";
**7.0以前:
Uri uri = Uri.fromFile(new File(filepath ))
Android7.0以前获取本地文件uri用的Uri.fromFile(new File(filePath)); 后会得到一个file://,这种方式呢7.0及以后的系统版本就用不了,且会报一个异常:
android.os.FileUriExposedException ****** exposed beyond app through Intent.getData()
**7.0以后:
Android7.0及以上系统版本由于共享文件权限的限制,需要用FileProvider.getUriForFile()
Android原生方法的定义:
public static Uri getUriForFile(@NonNull Context context, @NonNull String authority, @NonNull File file) {
FileProvider.PathStrategy strategy = getPathStrategy(context, authority);
return strategy.getUriForFile(file);
}
Uri uri = FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + ".fileprovider", file);
3.N版本以后,需要在AndroidManifest.xml添加provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider" //自定义的provider路径
android:exported="false" //是否独立
android:grantUriPermissions="true"> //是否拥有文件的临时权限
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" /> //自定义文件路径,此处需要手动在/res/新建xml文件夹/新建file_paths.xml
</provider>
指定路径和转换规则file_paths.xml
<?xml version = "1.0" encoding = "utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_storage"
path = "/external_storage"/>
</paths>
中可以定义以下子节点
| 子节点 | 对应路径 |
| files-path | Context.getFilesDir() |
| cache-path | Context.getCacheDir() |
|external-path |Environment.getExternalStorageDirectory() |
| external-files-path | Context.getExternalFilesDir(null) |
| external-cache-path | Context.getExternalCacheDir() |
ex:/storage/emulated/0/external_storage/love.mp4 对于此路径
子节点的书写为:
——/storage/emulated/0
name属性——自定义
path属性——/external_storage
书写规则要和
Uri uri = FileProvider.getUriForFile(MainActivity.this, getApplicationContext().getPackageName() + “.fileprovider”, file);
代码中的路径一致,否则会报空指针error