1、添加动态权限管理,<uses-permission android:name="android.permission.CAMERA" />
2、在res文件夹下,创建xml文件夹,接着创建file_paths.xml资源文件,内容如下:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="my_image" path="images"/> </paths>
其中 <external-path name="my_image" path="images"/> name=" ", path =" " ,可以自定义命名。
3、在配置文件 AndroidManifest.xml 添加下面代码
<provider
android:name="android.support.v4.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>
4、调起相机代码如下
//默认保存路径 private String mFolderString = "/images/"; private String mPath;
public void openCamera() { Intent intent = new Intent(); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { mPath = Environment.getExternalStorageDirectory().getPath() + mFolderString; mPath += System.currentTimeMillis() + ".jpg"; intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); // android 7.0以上 if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){ Uri contentUri = FileProvider.getUriForFile(ChainUpApp.appContext, "包名.fileprovider", new File(mPath)); intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri); }else { // android 7.0 以下 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPath))); } startActivityForResult(intent, CAMERA); } }