7

我正在开发一个需要扫描 QR 码并单击图片的应用程序,但有时会发生相机应用程序崩溃并且它说 Android 相机已停止工作并且需要重新启动设备才能正常运行。

我希望能够从我的活动中释放相机,以避免它在任何情况下稍后崩溃。需要帮助!

扫描代码:

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    try{
       Intent intent = new Intent("com.google.zxing.client.android.SCAN");
       intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
       startActivityForResult(intent, 0);
    }catch(Exception e){
         // ERROR
    }
} //End of onCreate

public void onActivityResult(int requestCode, int resultCode, Intent intent){
   if (requestCode == 0){
      if (resultCode == RESULT_OK){
         String contents = intent.getStringExtra("SCAN_RESULT");
         showPass(contents);
      }
      else if (resultCode == RESULT_CANCELED){
         showFail();
      } 
   } // End of If
} //End of onActivityResult

点击图片的代码:

public void takephoto(View v){
     Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
     startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if (requestCode == CAMERA_REQUEST){
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        //some action.
    }
}
4

1 回答 1

17

将以下代码放入您onDestroy的活动方法中:

protected void onDestroy(){

if(camera!=null){
            camera.stopPreview();
            camera.setPreviewCallback(null);

            camera.release();
            camera = null;
        }


}

如果您使用单独的 Preview 类,请在其中添加以下代码:

public void surfaceDestroyed(SurfaceHolder holder) {

        if(camera!=null){
            camera.stopPreview();
            camera.setPreviewCallback(null);

            camera.release();
            camera = null;
        }

    }
于 2013-05-23T04:43:04.603 回答