Mojtaba Safavi
Mojtaba Safavi

Reputation: 127

Mobile Flash Light Turn on with xamarin but it is not turned,Why?

My application is permitted to use the flash light and camera but it is not turned on. The device is a Nexus Samsung. I try to set FlashModeOn but it is not working. Please help me.

[Activity(Label = "TurnOnLight", MainLauncher = true, Icon = "@drawable/icon")]
public class Activity1 : Activity
{
    public void initCamera()
    {


        var b = FindViewById<Button>(Resource.Id.MyButton);
        try
        {
            if (!hasCamera)
            {

                mcamera = Camera.Open();
                hasCamera = true;

                p=mcamera.GetParameters();
                var s = p.Get(Camera.Parameters.FlashModeOn);

                   p.Set(Camera.Parameters.FlashModeTorch,0);
                   mcamera.SetParameters(p);


                mcamera.StartPreview();
            }
            else
            {
            }
        }
        catch (Exception exception)
        {

            hasCamera = false;
        }

    }

Upvotes: 4

Views: 6967

Answers (1)

Redth
Redth

Reputation: 5544

Here's the code I'm using in my ZXing.Net.Mobile project, and it's working fine for me. Keep in mind FlashModeOn is slightly different than FlashModeTorch:

https://github.com/Redth/ZXing.Net.Mobile/blob/master/src/ZXing.Net.Mobile/MonoForAndroid/ZXingSurfaceView.cs#L227-L267

public void Torch(bool on)
{
    if (!this.Context.PackageManager.HasSystemFeature(PackageManager.FeatureCameraFlash))
    {
        Android.Util.Log.Info("ZXING", "Flash not supported on this device");
        return;
    }

    if (camera == null)
    {
        Android.Util.Log.Info("ZXING", "NULL Camera");
        return;
    }

    var p = camera.GetParameters();
    var supportedFlashModes = p.SupportedFlashModes;

    if (supportedFlashModes == null)
        supportedFlashModes = new List<string>();

    var flashMode=  string.Empty;

    if (on)
    {
        if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeTorch))
            flashMode = Android.Hardware.Camera.Parameters.FlashModeTorch;
        else if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeOn))
            flashMode = Android.Hardware.Camera.Parameters.FlashModeOn;
    }
    else 
    {
        if ( supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeOff))
            flashMode = Android.Hardware.Camera.Parameters.FlashModeOff;
    }

    if (!string.IsNullOrEmpty(flashMode))
    {
        p.FlashMode = flashMode;
        camera.SetParameters(p);
    }
}

Upvotes: 1

Related Questions