Solution 1 :
You can register a broadcast receiver to receive a callback every time the volume button is pressed, then trigger an image capture each time. You can take a look at how the CameraX sample implements this.
The broadcast receiver will look as follows. Make sure to register and unregister it appropriately.
private val volumeDownReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.getIntExtra(KEY_EVENT_EXTRA, KeyEvent.KEYCODE_UNKNOWN)) {
KeyEvent.KEYCODE_VOLUME_DOWN -> // Trigger an image capture
}
}
}
Since -it seems- you’re using CameraX’s CameraView API, you can trigger an image capture by calling one of its takePicture
methods.
- takepicture(Executor, OnImageCaptureCallback)
- takePicture(OutputFileOptions, Executor, OnImageSavedCallback)
The image capture should only occur after the camera has been set up.
Problem :
I’m trying to make an app take a picture when the volume buttons are pressed, like snapchat and the like do. This app is using the CamaraX Library for camera functionality. Now as far as I can tell the CameraXView should let me set an onKeyListener as it extends frameLayout -> ViewGroup -> View. However, everything I’ve tried so far does not pick up the KeyEvents.
public class CameraXFragment extends LoggingFragment implements CameraFragment {
...
private CameraXView camera;
...
private void initControls() {
...
// This doesn't work
camera.setOnKeyListener((v, keyCode, event) -> {
Log.e(TAG, "KeyEvent please: " + keyCode);
return false;
});
...
// This does work
camera.setOnTouchListener((v, event) -> gestureDetector.onTouchEvent(event));
}
}
CameraXView does have a onTouchEvent
so I tried adding a onKeyDown
within it as well but that doesn’t seem to have worked.
The camera.setOnTouchEventLister
was not added by me so I don’t fully understand why that is working but mine isn’t.