上一篇文章已经写过安卓7.0跨应用的访问方法,这篇文章主要记录访问相机以及文件方法;
- 首先在AndroidManifest.xml中声明(必须在application标签内):
<!--适配安卓N跨应用访问-->
<provider
android:authorities="com.example.reportwork.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:grantUriPermissions="true"
tools:replace="android:authorities"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
在资源文件中新建XML文件夹并新建xml文件(file_paths.xml):
<paths>
<!-- root-path 从最底层目录开始 -->
<root-path path="" name="reportwork" />
</paths>
//getFilesDir()
<files-path name="name" path="path" />
//getCacheDir()
<cache-path name="name" path="path" />
//Environment.getExternalStorageDirectory()
<external-path name="name" path="path" />
//getExternalFilesDir()
<external-files-path name="name" path="path" />
//getExternalCacheDir()
<external-cache-path name="name" path="path" />
如果你不知道用什么,则直接使用root-path即可,代表从最底层根目录开始;
//打开文件
public static void openFile(Context context, File file, String contentType) throws ActivityNotFoundException {
if (context == null) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setDataAndType(getUriForFile(context, file), contentType);
if (!(context instanceof Activity)) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
}
//打开相机
public static void openCamera(Activity activity, File file, int requestCode) {
if (activity == null) {
return;
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriForFile(activity, file));
activity.startActivityForResult(intent, requestCode);
}
private static Uri getUriForFile(Context context, File file) {
if (context == null || file == null) {
throw new NullPointerException();
}
Uri uri;
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(context, "包名+.fileprovider", file);
} else {
uri = Uri.fromFile(file);
}
return uri;
}