I know that this is a very common problem on Stackoverflow which has quite a few answers, but none of them worked for me and quite a few other people which you can see in many posts like this one: Taking a picture with Android's Camera (API 19): onPictureTaken is not called
I browsed through quite a few questions similar to this one but never found a working fix.
I have a camera set up after the code from the android documentation and onPictureTaken() is never called after takePicture() is called. I debugged everything and the application always decides to be finished with it's onClick interaction after takePicture() is called and the callback is never executed. If you don't find a solution or don't want to read my nasty code, I would appreciate if you could post a working example from anywhere.
I'm sorry if there are any typos, here's my shortened code:
public final class MainActivity extends AppCompatActivity
implements SurfaceHolder.Callback, PictureCallback {
private ImageView imageView;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Camera mCamera;
private Parameters parameters;
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "Picture taken");
}
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//some preparation stuff here e.g. Permissions
mCamera = getCameraInstance();
imageView = (ImageView) findViewById(R.id.imageView);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button button = findViewById(R.id.button_id);
button.setOnClickListener(it - > {
if (mCamera != null) {
mCamera.takePicture(null, null, this);
}
}
}
private Camera getCameraInstance() {
Camera cam = null;
try {
cam = Camera.open();
} catch (Exception e) {
Log.d(TAG, "getCameraInstance() - Camera is not available");
return null;
}
return cam;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
mCamera.release();
mCamera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.d(TAG, "surfaceChanged()");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
I tried:
-letting the activity sleep to let the surface load properly
-tracking onPause() and onResume(), none of them were called
-inlining the pictureCallback
-posting takePicture() to the surfaceView