标签:manage set logs his gets sensor rac fas sum
1 //动作传感器:加速度传感器,重力传感器:
2 public class MainActivity extends Activity implements SensorEventListener {
3 private TextView tvAcceleromter;
4 private SensorManager sManager;
5 private float[] gravity = new float[3];
6
7 @Override
8 protected void onCreate(Bundle savedInstanceState) {
9 super.onCreate(savedInstanceState);
10 setContentView(R.layout.fragment_main);
11 tvAcceleromter = (TextView) findViewById(R.id.tv);
12 sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
13
14 }
15
16 // 传感器数据变化
17 @Override
18 public void onSensorChanged(SensorEvent event) {
19 // TODO Auto-generated method stub
20 switch (event.sensor.getType()) {
21 // 加速度 9.81m/s^2
22 case Sensor.TYPE_ACCELEROMETER:
23 final float alpha = (float) 0.8;// 系数
24 gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
25 gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
26 gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
27 // String accelerometer = "加速度:" + "X轴:" + event.values[0] + "Y轴:"
28 // + event.values[1] + "Z轴:" + (event.values[2] - 9.81);
29 // 去掉杂音
30 String accelerometer = "加速度:" + "X轴:"
31 + (event.values[0] - gravity[0]) + "Y轴:"
32 + (event.values[1] - gravity[1]) + "Z轴:"
33 + (event.values[2] - gravity[2]);
34 Log.i("--->>", String.valueOf(event.values[2] - gravity[2]));
35
36 // event.values[0]; X轴
37 // event.values[1]; Y轴
38 // event.values[2]; Z轴
39
40 tvAcceleromter.setText(accelerometer);
41 break;
42 // 重力
43 case Sensor.TYPE_GRAVITY:
44 gravity[0] = event.values[0];
45 gravity[1] = event.values[1];
46 gravity[2] = event.values[2];
47 break;
48
49 default:
50 break;
51 }
52 }
53
54 // 传感器精度变化
55 @Override
56 public void onAccuracyChanged(Sensor sensor, int accuracy) {
57 // TODO Auto-generated method stub
58
59 }
60
61 @Override
62 protected void onResume() {
63 // TODO Auto-generated method stub
64 super.onResume();
65 // 注册传感器
66 // 加速度
67 sManager.registerListener(this,
68 sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
69 SensorManager.SENSOR_DELAY_NORMAL);
70 // 重力
71 sManager.registerListener(this,
72 sManager.getDefaultSensor(Sensor.TYPE_GRAVITY),
73 SensorManager.SENSOR_DELAY_FASTEST);
74
75 }
76
77 @Override
78 protected void onPause() {
79 // TODO Auto-generated method stub
80 super.onPause();
81 // 不在截获传感器数据
82 sManager.unregisterListener(this);
83
84 }
85
86 }
标签:manage set logs his gets sensor rac fas sum
原文地址:http://www.cnblogs.com/my334420/p/6905632.html