Android8.0之后调用系统相机的配置

前一阵子将sdk升级到8.0之后,发现调用系统相机会崩溃,崩溃,崩溃,不得不上网查一查原因,结果还真是权限越来越严格啦。不得不做出修改。修改如下:

1.首先需要在manifest.xml中配置provider:


<provider
    android:authorities="包名.fileprovider"
    android:name="android.support.v4.content.FileProvider"
    android:grantUriPermissions="true"
    android:exported="false">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths"/>
provider>
2.在res/xml中配置filepaths.xml文件,内容如下:

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

3.写调用方法:

/**
 * 通过手机照相获取图片
 *
 * @param activity
 * @return 照相后图片的路径
 */
public void takePicture(final Activity activity, String name, final int requestCode) {
    Observable.just(name)
            .map(new Func1() {
                @Override
                public File call(String s) {
                    FileUtils.createDirFile(IMAGE_PATH);
                    String path = IMAGE_PATH + UUID.randomUUID().toString() + ".jpg";
                    if (!TextUtils.isEmpty(s)) {
                        path = IMAGE_PATH + s;
                    }
                    mTakePicturePath = path;
                    File file = FileUtils.createNewFile(path);
                    return file;
                }
            })
            .compose(activity.bindToLifecycle())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1() {
                @Override
                public void call(File file) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (file != null) {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriForFile(activity.getContext(),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.getApplicationContext(), "com.creditease.chuangxin.yifenqi.fileprovider", file);
    } else {
        uri = Uri.fromFile(file);
    }
    return uri;
}


你可能感兴趣的:(android,十年程序员的专栏)