Breaking News
Loading...
Friday, 31 August 2012

Determine light level, Sensor.TYPE_LIGHT.

06:34
Example to determine light level using Android light sensor:

Determine light level, Sensor.TYPE_LIGHT.


package com.example.androidsensor;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView textLIGHT_available, textLIGHT_reading;

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

textLIGHT_available
= (TextView)findViewById(R.id.LIGHT_available);
textLIGHT_reading
= (TextView)findViewById(R.id.LIGHT_reading);

SensorManager mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

Sensor LightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if(LightSensor != null){
textLIGHT_available.setText("Sensor.TYPE_LIGHT Available");
mySensorManager.registerListener(
LightSensorListener,
LightSensor,
SensorManager.SENSOR_DELAY_NORMAL);

}else{
textLIGHT_available.setText("Sensor.TYPE_LIGHT NOT Available");
}
}

private final SensorEventListener LightSensorListener
= new SensorEventListener(){

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_LIGHT){
textLIGHT_reading.setText("LIGHT: " + event.values[0]);
}
}

};

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />

<TextView
android:id="@+id/LIGHT_available"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/LIGHT_reading"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>


Related:
- Access temperature sensor, TYPE_TEMPERATURE and TYPE_AMBIENT_TEMPERATURE.

0 comments:

Post a Comment

 
Toggle Footer