android 传感器

 

 1 package com.itheima.sensor;
 2 
 3 import android.app.Activity;
 4 import android.hardware.Sensor;
 5 import android.hardware.SensorEvent;
 6 import android.hardware.SensorEventListener;
 7 import android.hardware.SensorManager;
 8 import android.os.Bundle;
 9 
10 public class MainActivity extends Activity implements SensorEventListener {
11 
12     private SensorManager manager;
13     private Sensor sensor;
14 
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.activity_main);
19         
20         manager = (SensorManager) getSystemService(SENSOR_SERVICE);
21         sensor = manager.getDefaultSensor(Sensor.TYPE_LIGHT);
22     }
23     
24     @Override
25     protected void onResume() {
26         super.onResume();
27         manager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);    // 注册监听器
28     }
29     
30     @Override
31     protected void onPause() {
32         super.onPause();
33         manager.unregisterListener(this);    // 注销监听
34     }
35 
36     @Override
37     public void onSensorChanged(SensorEvent event) {
38         /*
39         float x = event.values[0];
40         float y = event.values[1];
41         float z = event.values[2];
42         System.out.println("x = " + x + ", y = " + y + ", z = " + z);
43         */
44         
45         System.out.println(event.values[0]);
46     }
47 
48     @Override
49     public void onAccuracyChanged(Sensor sensor, int accuracy) {
50     }
51 
52 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。