代码
package com.example.sensor_text;
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.util.Log;
import android.widget.TextView;
import com.example.sensot_text.R;
public class MainActivity extends Activity {
private SensorManager systemService;
mylist lisn;
private TextView textView_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_text = (TextView) findViewById(R.id.TextView_text);
// 得到传感器服务(转换成传感器管理者)
systemService = (SensorManager) this.getSystemService(SENSOR_SERVICE);
// 获取所有传感器
// List<Sensor> sensorList =
// systemService.getSensorList(Sensor.TYPE_ALL);//获取全部传感器
// for (Sensor sensor : sensorList) {
// Log.e("tag", sensor.getName());
// }
// 获得方向传感器
Sensor defaultSensor = systemService
.getDefaultSensor(Sensor.TYPE_LIGHT);
// TYPE_LIGHT=5光线
// 3是方向
// 1监听改变器,2是传感器3,采样率
lisn = new mylist();
systemService.registerListener(lisn, defaultSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
public class mylist implements SensorEventListener {
// 当传感器数据变化的调用方法
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float f = event.values[0];
Log.e("tag", "光线" + f);
textView_text.setText("光线" + f);
// int f = (int) event.values[0];
// if(f>0&&f<90){
// textView_text.setText("东北");
// Log.e("tag", "东北");
// }else if(f>90&&f<180){
// textView_text.setText("东南");
// Log.e("tag", "东南");
// }
}
// 当传感器精度传感器(信号)
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
systemService.unregisterListener(lisn);
lisn = null;
super.onDestroy();
}
}
重要的一句话
systemService.registerListener(lisn, defaultSensor,
SensorManager.SENSOR_DELAY_NORMAL);