打开对话框不会打开相机应用程序

时间:2017-06-10 21:51:23

标签: android android-intent camera

我的应用程序中有一个按钮,它必须是打开相机,这是我的代码:

    mPhotoButton = (ImageButton) v.findViewById(R.id.crime_camera);
    final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    boolean canTakePhoto = mPhotoFile != null &&
            captureImage.resolveActivity(packageManager) != null;
    mPhotoButton.setEnabled(canTakePhoto);

    if (canTakePhoto) {
        Uri uri = Uri.fromFile(mPhotoFile);
        captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    }

    mPhotoButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivityForResult(captureImage, REQUEST_PHOTO);
        }
    });

当我按下它时,应用程序崩溃。

如果使用createChooser(),在运行应用程序并按下按钮时,打开对话框选择相机应用程序,它不会打开相机应用程序和应用程序崩溃。

我在清单中定义了相机的权限。

此代码正好运行另一台设备,但在我的设备(Galaxy S7 API24)中运行时出错。

1 个答案:

答案 0 :(得分:0)

这似乎是权限问题。 如果您在api级别23或更高级别上运行应用程序,则必须在运行时请求获得。

if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.CAMERA)) {

        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.CAMERA},
                MY_PERMISSIONS_REQUEST_CAMERA);

        // MY_PERMISSIONS_REQUEST_CAMERA is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}

然后处理结果

@Override
public void onRequestPermissionsResult(int requestCode,
        String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_CAMERA: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // camera task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

有关详细信息,请访问Android Runtime Permissions

相关问题