在上一篇中,讲到了怎么获取手机的传感器http://blog.csdn.net/nainai007/article/details/7615364,在这里是获取传感器的值。
要获取传感器的值,首先要为应用程序注册传感器时间,然后接受传感器传来的数据。
MainActivity的代码为:
- package com.nine.sensordemo;
- 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 MainActivity extends Activity {
- private SensorManager sm;
- private Sensor ligthSensor;
- private StringBuffer sb;
- private TextView tvValue;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- sb = new StringBuffer();
- tvValue = (TextView) findViewById(R.id.tvValue);
- //获取SensorManager对象
- sm = (SensorManager) getSystemService(SENSOR_SERVICE);
- //获取Sensor对象
- ligthSensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
- sm.registerListener(new MySensorListener(), ligthSensor, SensorManager.SENSOR_DELAY_NORMAL);
- }
- public class MySensorListener implements SensorEventListener {
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
- public void onSensorChanged(SensorEvent event) {
- //获取精度
- float acc = event.accuracy;
- //获取光线强度
- float lux = event.values[0];
- sb.append("acc ----> " + acc);
- sb.append("\n");
- sb.append("lux ----> " + lux);
- sb.append("\n");
- tvValue.setText(sb.toString());
- }
- }
- }
这里我主要获取手机的光线传感器,由于外界光线的变化,从而触发传感器时间的发生,程序通过获取传感器的精度和光线强度的值,并显示出来
转自: