ANDROID_MARS学习笔记_S05_006_距离传感器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ANDROID_MARS学习笔记_S05_006_距离传感器相关的知识,希望对你有一定的参考价值。

 

 1 import android.app.Activity;
 2 import android.content.Context;
 3 import android.hardware.Sensor;
 4 import android.hardware.SensorEvent;
 5 import android.hardware.SensorEventListener;
 6 import android.hardware.SensorManager;
 7 import android.os.Bundle;
 8 
 9 public class MainActivity extends Activity implements SensorEventListener {
10 
11      private SensorManager mSensorManager;
12       private Sensor mProximity;
13 
14       @Override
15       public final void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
17         setContentView(R.layout.main);
18 
19         // Get an instance of the sensor service, and use that to get an instance of
20         // a particular sensor.
21         mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
22         mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
23       }
24 
25       @Override
26       public final void onAccuracyChanged(Sensor sensor, int accuracy) {
27         // Do something here if sensor accuracy changes.
28       }
29 
30       @Override
31       public final void onSensorChanged(SensorEvent event) {
32         float distance = event.values[0];
33         System.out.println("distance--->" + distance);
34         System.out.println(mProximity.getMaximumRange());
35         // Do something with this sensor data.
36       }
37 
38       @Override
39       protected void onResume() {
40         // Register a listener for the sensor.
41         super.onResume();
42         mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
43       }
44 
45       @Override
46       protected void onPause() {
47         // Be sure to unregister the sensor when the activity pauses.
48         super.onPause();
49         mSensorManager.unregisterListener(this);
50       }
51 
52     
53 }

 

以上是关于ANDROID_MARS学习笔记_S05_006_距离传感器的主要内容,如果未能解决你的问题,请参考以下文章

ANDROID_MARS学习笔记_S01原始版_006_ListView

ANDROID_MARS学习笔记_S02_006_APPWIDGET3_AppWidget发送广播及更新AppWidget

ANDROID_MARS学习笔记_S04_006_用获取access_token,access_token_secrect

ANDROID_MARS学习笔记_S05_002_给传感器注册listener

ANDROID_MARS学习笔记_S05_001_用SensorManager获取传感器

ANDROID_MARS学习笔记_S05_004_过滤杂质,得到真正的加速度