How to use Light Sensor Android

This is a simple example to create an app using Light Sensor. Here you will learn basics of Light Sensor.

Follow these steps:

1. Create an android project.
2.Create a Main activity (MainLight.java)
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainLight extends Activity implements SensorEventListener {
    private SensorManager mgr;
    private Sensor light;
    private TextView text;
    private StringBuilder msg = new StringBuilder(2048);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        light = mgr.getDefaultSensor(Sensor.TYPE_LIGHT);
       
        text = (TextView) findViewById(R.id.text);
    }

    @Override
    protected void onResume() {
        mgr.registerListener(this, light, SensorManager.SENSOR_DELAY_NORMAL);
      super.onResume();
    }

    @Override
    protected void onPause() {
        mgr.unregisterListener(this, light);
      super.onPause();
    }

  public void onAccuracyChanged(Sensor sensor, int accuracy) {
    msg.insert(0, sensor.getName() + " accuracy changed: " + accuracy +
        (accuracy==1?" (LOW)":(accuracy==2?" (MED)":" (HIGH)")) + "\n");
    text.setText(msg);
    text.invalidate();
  }

  public void onSensorChanged(SensorEvent event) {
    msg.insert(0, "Got a sensor event: " + event.values[0] + " SI lux units\n");
    text.setText(msg);
    text.invalidate();
  }
}
3.  Create the resource res/layout/main.xml and paste following code
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"  android:layout_height="fill_parent" >
      <TextView  android:id="@+id/text" android:textSize="20sp"
        android:layout_width="fill_parent"  android:layout_height="wrap_content" />
    </LinearLayout>

 Thats it.
Note: You can run this apps only on live devices. But before installing this apps on your mobile, Please check the list of sensors running on you mobile

0 Comments
Disqus
Fb Comments
Comments :

0 comments:

Post a Comment