Android通过路径获取URI(全版本)

超、凢脫俗 2022-03-25 06:56 875阅读 0赞

1.res文件下新增xml文件夹
2.新增file_paths.xml文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <paths xmlns:android="http://schemas.android.com/apk/res/android">
  3. <external-path name="external_files" path="."/>
  4. </paths>

3.AndroidManifest配置(在application中)

  1. <application
  2. android:name=".BaseApplication"
  3. android:allowBackup="true"
  4. android:icon="@mipmap/ic_launcher"
  5. android:label="@string/app_name"
  6. android:supportsRtl="true"
  7. android:theme="@style/AppTheme">
  8. <provider
  9. android:name="android.support.v4.content.FileProvider"
  10. android:authorities="com.ztgf.share_se.fileprovider"
  11. android:exported="false"
  12. android:grantUriPermissions="true">
  13. <meta-data
  14. android:name="android.support.FILE_PROVIDER_PATHS"
  15. android:resource="@xml/file_paths" />
  16. </provider>
  17. </application>

4.判断系统应该使用什么方式进行调用(pakgename修改为当前包名)

  1. public static Uri getUri(Context context,String url){
  2. File tempFile = new File(url);
  3. //判断版本
  4. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //如果在Android7.0以上,使用FileProvider获取Uri
  5. try{
  6. return FileProvider.getUriForFile(context, "pakgename.fileprovider", tempFile);
  7. }catch (Exception e){
  8. e.printStackTrace();
  9. }
  10. } else { //否则使用Uri.fromFile(file)方法获取Uri
  11. return Uri.fromFile(tempFile);
  12. }
  13. return null;
  14. }

发表评论

表情:
评论列表 (有 0 条评论,875人围观)

还没有评论,来说两句吧...

相关阅读