1. 程式人生 > >Android8.0之後呼叫系統相機崩潰問題

Android8.0之後呼叫系統相機崩潰問題

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

<!--android8.0需要的配置,主要是呼叫相機-->
<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<String, File>() {
                @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.<File>bindToLifecycle())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<File>() {
                @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;
}