我正在开发一个需要扫描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 } } 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(); } } }
public void takephoto(View v) { Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent,CAMERA_REQUEST); } protected void onActivityResult(int requestCode,Intent data) { if (requestCode == CAMERA_REQUEST) { Bitmap photo = (Bitmap) data.getExtras().get("data"); // some action. } }
解决方法
将以下代码放在活动的onDestroy方法中:
protected void onDestroy(){ if(camera!=null){ camera.stopPreview(); camera.setPreviewCallback(null); camera.release(); camera = null; } }
public void surfaceDestroyed(SurfaceHolder holder) { if(camera!=null){ camera.stopPreview(); camera.setPreviewCallback(null); camera.release(); camera = null; } }