Android 正确关闭相机

2024-04-24

好吧,在过去的几周里,这种情况在我身上发生了几次,但我不知道如何解决它。基本上我的应用程序使用相机,但每隔一段时间,在应用程序上使用相机几次后,它有时会强制关闭,甚至无法与其他应用程序或手机上的默认相机一起使用。

我发现解决此问题的唯一方法是重新启动手机。

从我到目前为止所读到的内容来看,我知道我需要打电话

camera.release();

camera = null;

但有时我仍然会遇到强制关闭的错误,是否有人可能只是看一下也许我错过了一个camera.release();某处。

public class AndroidCamera extends Activity implements SurfaceHolder.Callback{

Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;

final int RESULT_SAVEIMAGE = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);



    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    getWindow().setFormat(PixelFormat.UNKNOWN);
    surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    controlInflater = LayoutInflater.from(getBaseContext());
    View viewControl = controlInflater.inflate(R.layout.control, null);
    LayoutParams layoutParamsControl 
        = new LayoutParams(LayoutParams.FILL_PARENT, 
        LayoutParams.FILL_PARENT);
    this.addContentView(viewControl, layoutParamsControl);

    Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
    buttonTakePicture.setOnClickListener(new Button.OnClickListener(){

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            camera.takePicture(myShutterCallback, 
                    myPictureCallback_RAW, myPictureCallback_JPG);


        }});

}

ShutterCallback myShutterCallback = new ShutterCallback(){

    public void onShutter() {
        // TODO Auto-generated method stub

    }};

PictureCallback myPictureCallback_RAW = new PictureCallback(){

    public void onPictureTaken(byte[] arg0, Camera arg1) {
        // TODO Auto-generated method stub

    }};

PictureCallback myPictureCallback_JPG = new PictureCallback(){

    public void onPictureTaken(byte[] arg0, Camera arg1) {
        // TODO Auto-generated method stub
        /*Bitmap bitmapPicture 
            = BitmapFactory.decodeByteArray(arg0, 0, arg0.length);  */
        int imageNum = 0;
        Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Punch");
        imagesFolder.mkdirs(); // <----
        String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
        File output = new File(imagesFolder, fileName);
        while (output.exists()){
            imageNum++;
            fileName = "image_" + String.valueOf(imageNum) + ".jpg";
            output = new File(imagesFolder, fileName);
        }

        Uri uriSavedImage = Uri.fromFile(output);
        imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);


        OutputStream imageFileOS;
        try {
            imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
            imageFileOS.write(arg0);
            imageFileOS.flush();
            imageFileOS.close();

            Toast.makeText(AndroidCamera.this, 
                    "Image saved", 
                    Toast.LENGTH_LONG).show();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Intent intent = new Intent(getBaseContext(), Punch.class);
        intent.putExtra("filepath",uriSavedImage.toString());
        //just using a request code of zero
        int request=0;
        startActivityForResult(intent,request); 
    }};

public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // TODO Auto-generated method stub
    if(previewing){
        camera.stopPreview();
        previewing = false;
    }

    if (camera != null){
        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.startPreview();
            previewing = true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            camera.release();
            e.printStackTrace();
        }
    }
}

public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub

    camera = Camera.open();
    try {
           Camera.Parameters parameters = camera.getParameters();
           if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
              // This is an undocumented although widely known feature
              parameters.set("orientation", "portrait");
              // For Android 2.2 and above
              camera.setDisplayOrientation(90);
              // Uncomment for Android 2.0 and above
              parameters.setRotation(90);
           } else {
              // This is an undocumented although widely known feature
              parameters.set("orientation", "landscape");
              // For Android 2.2 and above
              camera.setDisplayOrientation(0);
              // Uncomment for Android 2.0 and above
              parameters.setRotation(0);
           }
          camera.setParameters(parameters);
          camera.setPreviewDisplay(holder);
      } catch (IOException exception) {
         camera.release();


       }
        camera.startPreview();

    }


public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    if(previewing && camera != null) {
        if(camera!=null) {
            camera.stopPreview();
            camera.release();  
            camera = null;
        }
        previewing = false;
    }
}
}

logcat 给了我(还有更多,但我认为这是因为相机力对我关闭,所以应用程序的其余部分无法运行。

01-03 14:59:17.835: D/AndroidRuntime(16531): Shutting down VM

01-03 14:59:17.835: W/dalvikvm(16531): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)

01-03 14:59:17.845: E/AndroidRuntime(16531): FATAL EXCEPTION: main

01-03 14:59:17.845: E/AndroidRuntime(16531): java.lang.RuntimeException: Fail to connect to camera service


我在 onPause() 事件中关闭相机解决了同样的问题

@Override
protected void onPause()
{
    super.onPause();
    if (camera != null) {
        camera.stopPreview();
        camera.release();
        camera = null;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 正确关闭相机 的相关文章

随机推荐