停用相机闪光会导致应用崩溃

时间:2016-09-09 03:55:34

标签: android android-camera

我在处理相机闪光灯应用程序崩溃方面遇到了麻烦。当我第一次激活闪光灯时,它会点击图像但是再次尝试再次激活后相机应用程序会崩溃。

这是我的代码我已经采用了一个简单的按钮,其中应用了单击侦听器并调用了actionFlash()。我在代码中找不到错误。

actionFlash()

调用这两个函数
public void turnOnFlashLight()
{
    try
    {
        flashof.setImageResource(R.drawable.ic_flash_on_black_24dp);
        mCaptureRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
        mPreviewCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, null);

        Toast.makeText(this, "Flash activated", Toast.LENGTH_SHORT).show();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        Toast.makeText(this, "Flash failed:\n" + e.toString(), Toast.LENGTH_LONG).show();
    }
}

public void turnOffFlashLight()
{
    try
    {
        flashof.setImageResource(R.drawable.ic_flash_off_black_24dp);
        mCaptureRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF);
        mPreviewCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, null);
        Toast.makeText(this, "Flash disabled", Toast.LENGTH_SHORT).show();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        Toast.makeText(this, "Flash failed:\n" + e.toString(), Toast.LENGTH_LONG).show();
    }
}
单击按钮

时调用 actionFlash()
private void actionFlash()
{
    hasFlash = this.getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    if (!hasFlash) {
        AlertDialog alert = new AlertDialog.Builder(this).create();
        alert.setMessage("Sorry, your device doesn't support flash light!");
        alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alert.show();
        return;
    }
    else {  
        CameraManager mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
        try {
            String mCameraId = mCameraManager.getCameraIdList()[1];
            if (mCameraId.equals("1")) {    
                if (!isFlashOn) {                         
                    turnOnFlashLight();                        
                    isFlashOn = true;             
                    flashof.setImageResource(R.drawable.ic_flash_off_black_24dp);
                } else {                         
                    turnOffFlashLight();
                    isFlashOn = false;                       flashof.setImageResource(R.drawable.ic_flash_on_black_24dp);
                }
            }
        } catch (CameraAccessException e) {
            Toast.makeText(this, "Cannot access the camera.", Toast.LENGTH_SHORT).show();
            this.finish();
        }
    }
}

0 个答案:

没有答案