I have a simple problem:
I want a simple sketch to turn on/off the flashlight on my phone.
it would be nice, if it stays on, even if I turn off the screen of my phone.
Hi. Check this code if it works for you. Do not forget to give CAMERA permission.
If I remember well @akenaton pointed out that above Lollipop you have to ask for permission at runtime. I will look into that tomorrow, or maybe he himself can provide the code to add.
I ran the code on my Android 6 Samsung Galaxy S5 mini and it ran fine.
Then I tried it on my Sony XA2 with Android 9 and it doesn’t work.
So I added different colors for flashlight on/off(works fine on Android 6 as well) and it shows me the fitting colors on Android 9 but still no light.
Has anyone got any ideas on how to fix this?
PS: Camera permission is given in both cases.
@Bobby54 === how have you asked for permissions?
Not in the sketch code but in the drop down menu I ticked Camera and the file which is created for every android sketch(manifest I believe) also said
<uses-permission android:name="android.permission.CAMERA"(hope the spelling and syntax is correct, don’t have the code currently but it is definitely the right one).
Also I gave the sketch Camera permission after installing it on my phone.
I now tried it by adding:
The console logs that the sketch has camera permission but the flashlight still doesn’t turn on.
No not yet but I will, thanks.
I tried the original code on android 8.1, but it doesn’t work
the preview (i tried installing as app too) instantly crashes when trying to open
i gave the permission to camera and flashlight in the APDE sketch properties menu
Ha, turns out
Camera is deprecated since Android 5 which means that I probably only got lucky with
Camera working on Android 6 because it wasn’t completely disabled yet.
However there is a package named
camera2 (see here: https://developer.android.com/reference/android/hardware/camera2/package-summary).
In this package there is a class CameraManager.TorchCallback(see here: https://developer.android.com/reference/android/hardware/camera2/CameraManager.TorchCallback) with the function
setTorchMode(String camerID, boolean enabled) to control if the camera flashlight is enabled (then ´enabled = true´) or if the flashlight is turned off and available to be turned back on
enabled = false).
Addition: You can get the CameraId which is required by
setTorchMode() by using the
CameraCharacteristics class which is also included in the package.
The permission worked as you described above?