Monday, January 31, 2011

Get Light Sensor of Android device

Get Light Sensor of HTC wildfire

package com.exercise.AndroidLightSensor;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidLightSensor extends Activity {

SensorManager mySensorManager;
Sensor myLightSensor;

/** 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);

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());
}
}
}


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"
/>
</LinearLayout>


Download the files.

Next:
- Implement SensorEventListener to monitor Android light sensor

1 comment: