In my app I need to start the flashlight in an activity that is started by a BroadcastReceiver. It works fine if the app is in foreground or background and the screen is ON but if the screen is OFF (with or without keyguard lock), the app crashes.
Analysis: When screen is OFF, creating the camera object still succeeds, but Camera.startPreview() throws RuntimeException.
I can understand the motiviation to forbid camera activation when screen is off, but how can I just turn on/off the flashlight?
cam = Camera.open();
//...
try {
cam.startPreview();
}catch(RuntimeException e){
Log.w(TAG,"Failed opening camera preview. Maybe screen locked?: " + e.getMessage());
return;
}
Permissions:
<uses-permission android:name="android.permission.CAMERA" />
I tried using the FLASHLIGHT (undocumented) permission, but it is ignored during runtime.
Tested on Android 8.1, Xiaomi Mi A1 minSdkVersion 22
Links I searched:
flashlight not working,when device screen is off/sleep (android studio)
If the screen is off, the Activity won't actually be launched until its turned on. That's why the camera won't turn on. Instead, start a service to do it which can actually run immediately.