1. LightSensorActivity.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 LightSensorActivity extends Activity {
private SensorManager sensorMgr;
private TextView lux_msg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light_sensor);
initObject();
}
private void initObject() {
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
lux_msg = (TextView) findViewById(R.id.lux_Msg);
}
SensorEventListener light_sensor_listener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
StringBuilder sensorInfo = new StringBuilder();
sensorInfo.append("sensor name : " + sensor.getName() + "\n");
sensorInfo.append("sensor type : " + sensor.getType() + "\n");
sensorInfo.append("used power : " + sensor.getPower() + " mA\n");
sensorInfo.append("能感應的最大照度 : " + sensor.getMaximumRange() + "\n");
sensorInfo.append("values[0] = " + values[0] + "\n");
lux_msg.setText(sensorInfo);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
@Override
protected void onResume() {
super.onResume();
sensorMgr.registerListener(light_sensor_listener,
sensorMgr.getDefaultSensor(Sensor.TYPE_LIGHT),
SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void onPause() {
super.onPause();
sensorMgr.unregisterListener(light_sensor_listener);
}
}
2. activity_light_sensor.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/lux_Msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="@android:color/black"
android:textSize="20dp" />
</RelativeLayout>
沒有留言:
張貼留言