![]()
![]()
![]()
![]()
![]()
1 //位置传感器:邻近传感器:
2 public class MainActivity extends Activity implements SensorEventListener {
3 private TextView tView;
4 private SensorManager sManager;
5
6 @Override
7 protected void onCreate(Bundle savedInstanceState) {
8 super.onCreate(savedInstanceState);
9 setContentView(R.layout.fragment_main);
10 tView = (TextView) findViewById(R.id.tv);
11 sManager = (SensorManager) getSystemService(SENSOR_SERVICE);
12
13 }
14
15 // 传感器数据变化
16 @Override
17 public void onSensorChanged(SensorEvent event) {
18 // TODO Auto-generated method stub
19 switch (event.sensor.getType()) {
20
21 // 邻近传感器 --单位cm
22 case Sensor.TYPE_PROXIMITY:
23
24 tView.setText(String.valueOf(event.values[0]));
25 break;
26
27 default:
28 break;
29 }
30 }
31
32 // 传感器精度变化
33 @Override
34 public void onAccuracyChanged(Sensor sensor, int accuracy) {
35 // TODO Auto-generated method stub
36
37 }
38
39 @Override
40 protected void onResume() {
41 // TODO Auto-generated method stub
42 super.onResume();
43 // 注册传感器
44
45 // 邻近传感器
46 sManager.registerListener(this,
47 sManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
48 SensorManager.SENSOR_DELAY_UI);
49 }
50
51 @Override
52 protected void onPause() {
53 // TODO Auto-generated method stub
54 super.onPause();
55 // 不在截获传感器数据
56 sManager.unregisterListener(this);
57
58 }
59
60 }