简体   繁体   中英

Camera onActivityResult : resultCode is RESULT_CANCELED

I am new to Java and Android but I have an app that should take a picture from the camera and save it as a file. I can start the camera and take a picture but in onActivityResult the resultCode is always RESULT_CANCELED (0). First I had an android.os.FileUriExposedException error but I followed this blog and the problem seems to be solved : https://medium.com/@ali.muzaffar/what-is-android-os-fileuriexposedexception-and-what-you-can-do-about-it-70b9eb17c6d0

Though I still have a resultCode with value 0 (RESULT_CANCEL).

Below is the code where I start the camera activity :

private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");

    Uri uri = FileProvider.getUriForFile(
            this,
            this.getApplicationContext()
                    .getPackageName() + ".provider", file);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        intent.addFlags(FLAG_GRANT_WRITE_URI_PERMISSION);
    } else {
        List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            grantUriPermission(packageName, uri, FLAG_GRANT_WRITE_URI_PERMISSION | FLAG_GRANT_READ_URI_PERMISSION);
        }
    }

    startActivityForResult(intent, CAMERA_REQUEST_CODE);
}

And below is my onActivityResult (but resultCode is always 0) :

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Résultat de la capture de la photo
    if (requestCode == CAMERA_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {

最后,我按照此处给出的确切说明进行了操作, https://developer.android.com/training/camera/photobasics ,现在可以使用了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM