turn on/off the flash of the android phone

I have this code to turn the flash on / off but it doesn’t work, what am I wrong?

	AndroidJavaObject _camera = null;
	
	public void setFlashMode(string mode, Boolean enabled)
	{		
		if (_camera != null) {
			AndroidJavaObject cameraParameters = _camera.Call<AndroidJavaObject>("getParameters");
			cameraParameters.Call("setFlashMode",mode);			
			_camera.Call("setParameters",cameraParameters);
		}
	}
	
	public  void LEDOn() {
		setFlashMode("torch", true);
	}

	public void LEDOff() {
		setFlashMode("off", false);
	}
}

Uhm where and when do you actually initialize your _camera variable? Did you actually use the static open method on the Camera class retrieve the first backfacing Camera object? Your code doesn’t show this. If the code you’ve posted is all you have, of course it won’t work.

You would need something like this:

using(var camClass = new AndroidJavaClass("android.hardware.Camera"))
{
    _camera = camClass.CallStatic("open");
}

I have never used the Camera class. Maybe you can do all this inside your “setFlashMode” method because you should call release on the camera object once you don’t use it anymore. So I would suggest one of those two approaches:

public void setFlashMode(bool aEnabled)
{        
    using(var camClass = new AndroidJavaClass("android.hardware.Camera"))
    using(var cam = camClass.CallStatic("open"))
    {
        if (cam == null)
            return;
        var cameraParameters = cam.Call<AndroidJavaObject>("getParameters");
        cameraParameters.Call("setFlashMode", aEnabled?"torch":"off");
        cam.Call("setParameters", cameraParameters);
        cam.Call("release");
    }
}

If that doesn’t work (because you might need to keep the camera object alive) you would do something like

public void setFlashMode(bool aEnabled)
{
    if (aEnabled)
    {
        if (_camera == null)
        {
            using(var camClass = new AndroidJavaClass("android.hardware.Camera"))
                _camera = camClass.CallStatic("open"))
        }
        var cameraParameters = _camera.Call<AndroidJavaObject>("getParameters");
        cameraParameters.Call("setFlashMode", "torch");
        _camera.Call("setParameters", cameraParameters);
    }
    else if (_camera != null)
    {
        var cameraParameters = _camera.Call<AndroidJavaObject>("getParameters");
        cameraParameters.Call("setFlashMode", "off");
        _camera.Call("setParameters", cameraParameters);
        _camera.Call("release");
        _camera.Dispose();
        _camera = null;
    }
}

The first approach would be the better one if it works.

the two codes entered are executed but the torch does not turn on
Does not work.
I will have to look for a different solution.
@Bunny83