使用Android的相机

时间:2017-08-18 06:11:20

标签: android android-camera

我正在尝试将相机与我的应用程序一起使用,但是当我按下按钮时,应用程序崩溃并在Android监视器中显示以下消息:

java.lang.SecurityException: Permission Denial: starting Intent { 
act=android.media.action.IMAGE_CAPTURE 
cmp=com.android.camera2/com.android.camera.CaptureActivity } from 
ProcessRecord{bd3e6b7 4753:com.demonsystem.trackingticket/u0a94} (pid=4753, 
uid=10094) with revoked permission android.permission.CAMERA

这是我主要活动中的代码:

btnCamara.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(i,0); <-- here shows the error
                ocultar();
            }
        });

这些是权限:

private void checkCameraPermission() {
        int permissionCheck = ContextCompat.checkSelfPermission(
                this, Manifest.permission.CAMERA);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            Log.i("Mensaje", "No se tiene permiso para la camara!.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 225);
        } else {
            Log.i("Mensaje", "Tienes permiso para usar la camara.");
        }
    }

这些是我在清单中写的用法:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

enter image description here

2 个答案:

答案 0 :(得分:1)

btnCamara.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick (View view){
    if (hasPermissionUseCamera()) {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(i, 0); 
        ocultar();
    }
  }
}

public boolean hasPermissionUseCamera() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, 0);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        return true;
    }
}

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    switch (requestCode) {
        case 0: {
            if (getActivity().checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(i, 0); 
                ocultar();
            } else {
                Toast.makeText(getActivity(), "Access Denied", Toast.LENGTH_SHORT).show();
            }
            break;
        }
    }
}

答案 1 :(得分:0)

在点火之前,Image_Capture操作只需检查您的应用是否拥有此权限。