安卓获取uri 适配安卓各版本
一.安卓7.0以上系统
1.在AndroidManifest中配置
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/update_paths" /> </provider>
2.在安卓res目录下配置device_filter.xml文件
文件内容如下: <?xml version="1.0" encoding="utf-8"?> <paths> <root-path name="root" path="" /> </paths>
3.获取uri
/** * 根据文件路径获取uri * @param context * @param filepath * @return */ public static Uri getUri(Context context,String filepath){ Uri u= null; try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { u = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", new File(filepath)); } else { u=Uri.parse("file://" + filepath); } } catch (Exception e) { e.printStackTrace(); } return u; } /** * 根据文件获取uri * @param context * @param file * @return */ public static Uri getUri(Context context,File file){ if(file==null){ return null; } Uri u=null; if (Build.VERSION.SDK_INT >= 24) { if(context==null){ return null; } u = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file); } else { u=Uri.fromFile(file); } return u; }