PictureCallback.onPictureTaken never called

前端 未结 3 1237
别那么骄傲
别那么骄傲 2020-12-10 13:06

I am writing an application that needs pictures taken with the camera. The problem occurs when I try to take an actual picture. Here\'s the code that is troubling me:

<
3条回答
  •  余生分开走
    2020-12-10 14:04

    I was having this exact problem. After much debugging I finally realized that the stupid Camera object was getting garbage collected before it had a chance to call the callbacks!

    I fixed it by creating a hard reference to the Camera object that I was using. I made it a member of my PictureTaker class, set it before calling takePicture() and then null it out in the jpeg callback after I receive my data. Then I just have to make sure my PictureTaker object won't get gc'd itself, which I do by keeping it around in my Application subclass for the life of the process.

    This always works on my Droid RAZR:

    public class PictureTaker implements Camera.PictureCallback
    {
      private Camera mCam;
      private MyApp theApp;
    
      public PictureTaker(MyApp app)
      {
         theApp = app;
      }
    
      public void takePicture()
      {
         try
         {
            mCam = Camera.open();
         }
         catch (Exception e)
         {
            System.out.println("Problem opening camera! " + e);
            return;
         }
    
         if (mCam == null)
         {
            System.out.println("Camera is null!");
            return;
         }
    
         try
         {
            SurfaceView view = MyApp.getPreviewSurface(); // my own fcn
            mCam.setPreviewDisplay(view.getHolder());
            mCam.startPreview();
            mCam.takePicture(null, null, this);
         }
         catch (Exception e)
         {
            System.out.println("Problem taking picture: " + e);
         }
      }
    
      public void onPictureTaken(byte[] data, Camera cam)
      {
         theApp.jpegPictureData(data);  // also my own fcn
    
         cam.stopPreview();
         cam.release();
    
         mCam = null;
      }
    }
    

提交回复
热议问题