如何从相机意图中获取URI?

时间:2018-10-07 09:12:18

标签: java android camera uri

我已经阅读了这篇文章:Get uri from camera intent in android,但这对我没有帮助。

为了处理摄像头请求,我使用了以下代码:

    public void startCamera() {
    if (PermissionUtils.requestPermission(
            this,
            CAMERA_PERMISSIONS_REQUEST,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA)) {
        //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        Uri photoUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", getCameraFile());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, CAMERA_IMAGE_REQUEST);
    }
}


 public File getCameraFile() {
    File dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    return new File(dir, FILE_NAME);
}


    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAMERA_IMAGE_REQUEST && resultCode == RESULT_OK) {
        Uri photoUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", getCameraFile());
        uploadImage(photoUri);
    }
}

当我调用函数“ startCamera”时,应用程序崩溃,并在行处给我错误:

Uri photoUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", getCameraFile());"

有帮助吗?谢谢!

1 个答案:

答案 0 :(得分:0)

已修复,方法是将其添加到“ AndroidManifest”中:

        <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>