Android takePicture没有调用onPictureTaken()的回调方法

时间:2014-04-26 19:30:41

标签: java android callback camera

我正在制作一个隐藏的相机应用程序,但我拍照时遇到了一些问题。

当我调试应用程序时,我可以看到可以调用takePicture,但它不会调用pictureCallback类。

我正在上课,正在等待你的帮助。

public class TakePhotoClass {

private final String LOG_TAG="Photo Taker Class";      

private Context context;

private Camera cam;
private Camera.PictureCallback pictureCallback;

private AudioManager audioManager;

public TakePhotoClass(Context con) {
    // TODO Auto-generated constructor stub

    context=con;

    audioManager=(AudioManager) con.getSystemService(Context.AUDIO_SERVICE);
}

public void takePhoto(){
    prepareCamera();

    audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);

    try{
        cam.startPreview();
        cam.takePicture(null, null, pictureCallback);

    }catch(Exception ex)
    {
        Log.e(LOG_TAG, "Couldn't be taken photo. Error message: "+ex.getLocalizedMessage());
    }

}

private void prepareCamera(){
    cam=Camera.open();

    Camera.Parameters param=cam.getParameters();

    param.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
    param.setJpegQuality(100);
    param.setFocusMode(param.FOCUS_MODE_AUTO);
    param.setPictureFormat(ImageFormat.JPEG);

    cam.setParameters(param);


    SurfaceView view=new SurfaceView(context);

    try {
        cam.setPreviewDisplay(view.getHolder());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e(LOG_TAG, "Can not set surface");
    }


    setCallback();

}

private void setCallback(){
    pictureCallback=new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub

            try{

                File parentFolder=new File(Environment.getExternalStorageDirectory()+"/Agent Cam/Photo");

                File photoFile=new File(parentFolder,"photo_"+getPhotoTime()+".jpg");

                if(!photoFile.exists())
                    photoFile.mkdirs();

                FileOutputStream stream=new FileOutputStream(photoFile);

                stream.write(data);
                stream.flush();
                stream.close();

                audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);

                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+Environment.getExternalStorageDirectory())));

                camera.release();
            }catch(Exception ex)
            {
                Log.e(LOG_TAG, "Photo coluldn't be saved. Error message: "+ex.getLocalizedMessage());
            }
        }
    };
}

private String getPhotoTime(){
    SimpleDateFormat sdf=new SimpleDateFormat("ddMMyy_hhmmss");

    return sdf.format(new Date());
}   

}

1 个答案:

答案 0 :(得分:0)

Camera.PictureCallback的onPictureTaken方法是异步调用的(请参阅takePicture),您的应用应该等待它被调用。