Retrieve data from Light Sensor with Xamarin Android

Sensors are very interesting things when you are going to develop an exciting software that expose output to environment changes of the device. Today I wanted to check light sensor of my vintage android phone and did it with Xamarin. The code is below

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Hardware;

namespace SensorSample
{
  [Activity (Label = "SensorSample", MainLauncher = true, Icon = "@drawable/icon")]
  public class MainActivity : Activity, Android.Hardware.ISensorEventListener
  {
    private SensorManager _senMan;
    float lightSensorValue;
    protected override void OnCreate (Bundle bundle)
    {
      base.OnCreate (bundle);
      SetContentView (Resource.Layout.Main);

      Button button = FindViewById<Button> (Resource.Id.myButton);

      _senMan = (SensorManager)GetSystemService (Context.SensorService);
      Sensor sen = _senMan.GetDefaultSensor (SensorType.Light);
      _senMan.RegisterListener (this, sen, Android.Hardware.SensorDelay.Game);

      button.Click += delegate {
        Toast.MakeText(this, sen.Vendor,ToastLength.Long).Show();
      };
    }
      

    public void OnSensorChanged(SensorEvent s)
    {
      s.Sensor = _senMan.GetDefaultSensor (SensorType.Light);
      lightSensorValue = s.Values [0];
      Toast.MakeText(this, lightSensorValue.ToString("0.00"),ToastLength.Long).Show();
    }

    public void OnAccuracyChanged (Sensor sensor, SensorStatus accuracy)
    {
      //throw new NotImplementedException ();
    }
  }
}
Advertisements

2 thoughts on “Retrieve data from Light Sensor with Xamarin Android

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s