我正在开发一个需要扫描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, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
// some action.
}
}
答案 0 :(得分: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;
}
}