After one click on capture button, I need to take images at regular intervals. I have written the code using Handler. But what happens now is that, I need to click button at each capture of images. What I want is to click on the button only once and then process to be automated. That is to capture images at regular intervals without any further clickings. How can I achieve this. Thank You.
public class MyCamera extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
mCamera.takePicture(null,null,mPicture);
}
};
handler.postDelayed(r, 15000);
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, e.getMessage());
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
};
}
In your onclick listener,
handler.removeCallbacks(runnable);
handler.postDelayed(runnable,15000);
And declare your handler and runnable like this, outside the onclick listener,
Handler handler=new Handler();
Runnable runnable=new Runnable() {
@Override
public void run() {
mCamera.takePicture(null, null, mPicture);
handler.postDelayed(this, 15000);
}
};
EXPLANATION
When you click on your camera button,a handler will be attached, which will take a picture after 15 minutes and we attach the same runnable to the handler to repeat it task. I have user handler.removeCallbacks(runnable);
to avoid multiple handlers if user clicks on the camera button again. Probably you can remove the onCickListener it self. Also, you should call handler.removeCallbacks(runnable);
when your activity/camera is not available.