Thursday, July 7, 2011

Monitor the light sensor in Android

Haven't tried it yet, but
From this post

Only two files:
Code:
package com.exercise.AndroidLightSensor;

import android.app.Activity;
import android.content.Context;
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 AndroidLightSensor extends Activity {
 
 SensorManager mySensorManager;
 Sensor myLightSensor;
 TextView textLightSensorData;
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
    
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       TextView textLightSensor = (TextView)findViewById(R.id.lightsensor);
       textLightSensorData = (TextView)findViewById(R.id.lightsensordata);
      
       mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
       myLightSensor = mySensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
      
       if (myLightSensor == null){
        textLightSensor.setText("No Light Sensor!");
       }else{
        textLightSensor.setText(myLightSensor.getName());
        
        mySensorManager.registerListener(lightSensorEventListener,
          myLightSensor,
          SensorManager.SENSOR_DELAY_NORMAL);
       }
   }
  
   SensorEventListener lightSensorEventListener
    = new SensorEventListener(){

   @Override
   public void onAccuracyChanged(Sensor arg0, int arg1) {
    // TODO Auto-generated method stub
    
   }

   @Override
   public void onSensorChanged(SensorEvent arg0) {
    // TODO Auto-generated method stub
    if(arg0.sensor.getType()==Sensor.TYPE_LIGHT){
     textLightSensorData.setText("Light Sensor Date:"
       + String.valueOf(arg0.values[0]));
    }
   }};
}


And layout:
<?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:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<TextView 
   android:id="@+id/lightsensor"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView 
   android:id="@+id/lightsensordata"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
</LinearLayout>

No comments:

Post a Comment