Android开发——使用传感器

1.Sensor相关的类:SensorSensorManager

常用传感器类型

  • TYPE_ALL——A constant describing all sensor types.
  • TYPE_ACCELEROMETE
  • TYPE_LINEAR_ACCELERATION
  • TYPE_GRAVITY
  • TYPE_GYROSCOPE
  • TYPE_MAGNETIC_FIELD
  • TYPE_ORIENTATION——已弃用
  • TYPE_MOTION_DETECT——Requires API level 24 (Android 7.0, Nougat)
  • TYPE_SIGNIFICANT_MOTION
  • TYPE_STATIONARY_DETECT
  • TYPE_STEP_COUNTER
  • TYPE_STEP_DETECTOR
  • TYPE_HEART_BEAT——A constant describing a motion detect sensor.Requires API level 24 (Android 7.0, Nougat)
  • TYPE_HEART_RATE
  • TYPE_PRESSURE
  • TYPE_PROXIMITY
  • TYPE_TEMPERATURE——已弃用
  • TYPE_AMBIENT_TEMPERATURE
  • TYPE_RELATIVE_HUMIDITY
  • TYPE_LIGHT

常用传感器方法:

  • getVendor()——传感器生产商
  • getName()——传感器名称
  • getId()——传感器ID,Requires API level 24 (Android 7.0, Nougat)
  • getType()——传感器类型
  • getStringType()——传感器类型
  • getVersion()——传感器版本号
  • getResolution()——传感器精度
  • isWakeUpSensor()——Returns true if the sensor is a wake-up sensor.

Always make sure to disable sensors you don't need, especially when your activity is paused. Failing to do so can drain the battery in just a few hours.
Note that the system will not disable sensors automatically when the screen turns off.

常量值

  • GRAVITY_EARTH Value——9.80665f
  • STANDARD_GRAVITY——9.80665f
  • PRESSURE_STANDARD_ATMOSPHERE——1013.25f(hPa)
  • SENSOR_ALL——A constant that includes all sensors
  • SENSOR_ACCELEROMETER
  • SENSOR_MAGNETIC_FIELD——All values are in micro-Tesla (uT) and measure the ambient magnetic field in the X, Y and -Z axis.
  • SENSOR_ORIENTATION
  • SENSOR_ORIENTATION_RAW
  • SENSOR_PROXIMITY
  • SENSOR_TEMPERATURE
  • SENSOR_LIGHT
  • SENSOR_DELAY_FASTEST——get sensor data as fast as possible
  • SENSOR_DELAY_GAME——rate suitable for games
  • SENSOR_DELAY_NORMAL——rate (default) suitable for screen orientation changes
  • SENSOR_DELAY_UI——rate suitable for the user interface

常用方法:

  • int getSensors()——return available sensors
  • getSensorList(type: Int)——return a list of sensors matching the asked type:MutableList<Sensor>.
  • getDefaultSensor(type: Int)——return default sensor
  • getDefaultSensor(type: Int, wakeUp: Boolean)
  • registerListener(listener: SensorListener, sensors: Int)——Registers a SensorListener for given sensors.
  • registerListener(listener: SensorListener!, sensors: Int, rate: Int)——Registers a SensorListener for given sensors.
  • registerListener(listener: SensorEventListener, sensor: Sensor, samplingPeriodUs: Int)——Registers a SensorEventListener for the given sensor at the given sampling frequency.
  • unregisterListener(listener: SensorListener)——Unregisters a listener for all sensors.
  • unregisterListener(listener: SensorListener, sensors: Int)——Unregisters a listener for the sensors with which it is registered.
  • unregisterListener(listener: SensorEventListener!)——Unregisters a listener for all sensors. 
  • unregisterListener(listener: SensorEventListener!, sensor: Sensor)——Unregisters a listener for the sensors with which it is registered.

2.传感器数据处理:SensorEvent属性

  • accuracy——The accuracy of this event.
  • sensor——The sensor that generated this event.
  • timestamp——The time in nanosecond at which the event happened.
  • values——The length and contents of the values array depends on which sensor type is being monitored

Sensor.TYPE_ACCELEROMETER: All values are in SI units (m/s^2)

  • values[0]: Acceleration minus Gx on the x-axis
  • values[1]: Acceleration minus Gy on the y-axis
  • values[2]: Acceleration minus Gz on the z-axis

Sensor.TYPE_ORIENTATION: All values are angles in degrees.

  • values[0]: Azimuth, angle between the magnetic north direction and the y-axis, around the z-axis (0 to 359). 0=North, 90=East, 180=South, 270=West
  • values[1]: Pitch, rotation around x-axis (-180 to 180), with positive values when the z-axis moves toward the y-axis.
  • values[2]: Roll, rotation around the y-axis (-90 to 90) increasing as the device moves clockwise.
  • Note: This definition is different from yaw, pitch and roll used in aviation where the X axis is along the long side of the plane (tail to nose).
  • Note: This sensor type exists for legacy reasons, please use rotation vector sensor type and getRotationMatrix() in conjunction with remapCoordinateSystem() and getOrientation() to compute these values instead.
  • Important note: For historical reasons the roll angle is positive in the clockwise direction (mathematically speaking, it should be positive in the counter-clockwise direction).

3.接口:SensorListenerSensorEventListener

以下两个方法在SensorListener中已弃用,可以在SensorEvenListener中使用

  • int onAccuracyChanged(sensor: Int, accuracy: Int) This class was deprecated in API level 21.
  • int onSensorChanged(sensor: Int, values: FloatArray!) This class was deprecated in API level 21.

4.列出手机所有传感器信息代码

 1 package com.lee.sensor;
 2 
 3 import android.app.Activity;
 4 import android.hardware.Sensor;
 5 import android.hardware.SensorManager;
 6 import android.os.Bundle;
 7 import android.widget.TextView;
 8 
 9 import java.util.List;
10 
11 public class ListAllSensorsActivity extends Activity {
12     @Override
13     protected void onCreate(Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
15         setContentView(R.layout.activity_list_all_sensors);
16 
17         // 显示传感器信息的组件
18         TextView textView = findViewById(R.id.sensors_list_tv);
19 
20         // 从系统服务中获得传感器管理器
21         SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
22 
23         // 从传感器管理器中获得全部的传感器列表
24         List<Sensor> allSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
25 
26         // 显示每个传感器的信息
27         StringBuilder sensorsInfo = new StringBuilder("手机有"+allSensors.size()+"个传感器,分别是:\n\n");
28         for(Sensor s:allSensors){
29             switch(s.getType()){
30                 case Sensor.TYPE_ACCELEROMETER:
31                     sensorsInfo.append("加速度传感器");
32                     break;
33                 case Sensor.TYPE_LINEAR_ACCELERATION:
34                     sensorsInfo.append("线性加速度传感器");
35                     break;
36                 case Sensor.TYPE_GRAVITY:
37                     sensorsInfo.append("重力传感器");
38                     break;
39                 case Sensor.TYPE_GYROSCOPE:
40                     sensorsInfo.append("陀螺仪传感器");
41                     break;
42                 case Sensor.TYPE_ORIENTATION:
43                     sensorsInfo.append("方向传感器");
44                     break;
45                 case Sensor.TYPE_MOTION_DETECT:
46                     sensorsInfo.append("运动状态检测传感器");
47                     break;
48                 case Sensor.TYPE_SIGNIFICANT_MOTION:
49                     sensorsInfo.append("剧烈运动检测传感器");
50                     break;
51                 case Sensor.TYPE_STATIONARY_DETECT:
52                     sensorsInfo.append("静止状态检测传感器");
53                     break;
54                 case Sensor.TYPE_STEP_COUNTER:
55                     sensorsInfo.append("步数计数器");
56                     break;
57                 case Sensor.TYPE_STEP_DETECTOR:
58                     sensorsInfo.append("步伐检测器");
59                     break;
60                 case Sensor.TYPE_MAGNETIC_FIELD:
61                     sensorsInfo.append("电磁场传感器");
62                     break;
63                 case Sensor.TYPE_LIGHT:
64                     sensorsInfo.append("环境光线传感器");
65                     break;
66                 case Sensor.TYPE_PRESSURE:
67                     sensorsInfo.append("压力传感器");
68                     break;
69                 case Sensor.TYPE_PROXIMITY:
70                     sensorsInfo.append("距离传感器");
71                     break;
72                 case Sensor.TYPE_AMBIENT_TEMPERATURE:
73                     sensorsInfo.append("温度传感器");
74                     break;
75                 case Sensor.TYPE_RELATIVE_HUMIDITY:
76                     sensorsInfo.append("相对湿度传感器");
77                     break;
78                 default:
79                     sensorsInfo.append("未知传感器");
80                     break;
81             }
82             // 下面两行合并有warning
83             String curSensorInfo = "\n设备类型码:"+s.getType()+"\n设备名称:"+s.getName()+"\n设备版本:"+s.getVersion()+"\n供应商:"+s.getVendor()+"\n\n";
84             sensorsInfo.append(curSensorInfo);
85         }
86         textView.setText(sensorsInfo);
87     }
88 }
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ListAllSensorsActivity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/sensors_list_tv"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""/>

</ScrollView>

 5.测试加速度,电磁场,方向传感器代码

 1 package com.lee.sensor;
 2 
 3 import android.app.Activity;
 4 import android.content.Context;
 5 import android.hardware.Sensor;
 6 import android.hardware.SensorEvent;
 7 import android.hardware.SensorEventListener;
 8 import android.hardware.SensorManager;
 9 import android.os.Bundle;
10 import android.widget.TextView;
11 
12 public class TestSensorActivity extends Activity implements SensorEventListener {
13 
14     private SensorManager mSensorManager;
15     private TextView mTextViewAcceleration;
16     private TextView mTextViewOrientation;
17     private TextView mTextViewMagneticField;
18     @Override
19     protected void onCreate(Bundle savedInstanceState) {
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.activity_test_sensor);
22 
23         mTextViewAcceleration = findViewById(R.id.accelerometer_tv);
24         mTextViewOrientation = findViewById(R.id.orientation_tv);
25         mTextViewMagneticField = findViewById(R.id.magnetic_field_tv);
26 
27         mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);  // 获取SensorManager服务
28     }
29 
30     @Override
31     protected void onResume() {
32         super.onResume();
33         // 为加速度传感器注册监听器
34         mSensorManager.registerListener(TestSensorActivity.this,mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_UI);
35         // 为电磁场传感器注册监听器
36         mSensorManager.registerListener(TestSensorActivity.this,mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),SensorManager.SENSOR_DELAY_UI);
37         // 为方向传感器注册监听器
38         mSensorManager.registerListener(TestSensorActivity.this,mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_UI);
39     }
40 
41     @Override
42     protected void onStop() {
43         super.onStop();
44         // 取消注册所有传感器
45         mSensorManager.unregisterListener(TestSensorActivity.this);
46     }
47 
48     // 当传感器的值改变时回调此方法
49     @Override
50     public void onSensorChanged(SensorEvent event) {
51         StringBuilder str = new StringBuilder();
52         switch (event.sensor.getType()){
53             case Sensor.TYPE_ACCELEROMETER:
54                 str.append("X方向上的加速度:");
55                 str.append(event.values[0]);
56                 str.append("\nY方向上的加速度:");
57                 str.append(event.values[1]);
58                 str.append("\nZ方向上的加速度:");
59                 str.append(event.values[2]);
60                 mTextViewAcceleration.setText(str);
61                 break;
62             case Sensor.TYPE_MAGNETIC_FIELD:
63                 str.append("X方向上的磁感应强度:");
64                 str.append(event.values[0]);
65                 str.append("\nY方向上的磁感应强度:");
66                 str.append(event.values[1]);
67                 str.append("\nZ方向上的磁感应强度:");
68                 str.append(event.values[2]);
69                 mTextViewMagneticField.setText(str);
70                 break;
71             case Sensor.TYPE_ORIENTATION:
72                 str.append("绕Z轴转过的角度:");
73                 str.append(event.values[0]);
74                 str.append("\n绕X轴转过的角度:");
75                 str.append(event.values[1]);
76                 str.append("\n绕Y轴转过的角度:");
77                 str.append(event.values[2]);
78                 mTextViewOrientation.setText(str);
79                 break;
80         }
81     }
82 
83     // 当传感器精度改变时回调此方法
84     @Override
85     public void onAccuracyChanged(Sensor sensor, int accuracy) { }
86 }
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout
 3     xmlns:android="http://schemas.android.com/apk/res/android"
 4     xmlns:tools="http://schemas.android.com/tools"
 5     tools:context=".TestSensorActivity"
 6     android:layout_width="match_parent"
 7     android:layout_height="match_parent"
 8     android:orientation="vertical">
 9 
10     <TextView
11         android:layout_width="wrap_content"
12         android:layout_height="wrap_content"
13         android:text="@string/acceleration_sensor"
14         android:textSize="20sp"/>
15 
16     <TextView
17         android:id="@+id/accelerometer_tv"
18         android:layout_width="match_parent"
19         android:layout_height="wrap_content"
20         android:layout_marginTop="10dp"
21         android:textSize="20sp"/>
22 
23     <TextView
24         android:layout_width="wrap_content"
25         android:layout_height="wrap_content"
26         android:layout_marginTop="40dp"
27         android:text="@string/magnetic_field_sensor"
28         android:textSize="20sp"/>
29 
30     <TextView
31         android:id="@+id/magnetic_field_tv"
32         android:layout_width="match_parent"
33         android:layout_height="wrap_content"
34         android:layout_marginTop="10dp"
35         android:textSize="20sp"/>
36 
37     <TextView
38         android:layout_width="wrap_content"
39         android:layout_height="wrap_content"
40         android:layout_marginTop="40dp"
41         android:text="@string/orientation_sensor"
42         android:textSize="20sp"/>
43 
44     <TextView
45         android:id="@+id/orientation_tv"
46         android:layout_width="match_parent"
47         android:layout_height="wrap_content"
48         android:layout_marginTop="10dp"
49         android:textSize="20sp"/>
50 
51 </LinearLayout>

猜你喜欢

转载自www.cnblogs.com/Lee-01/p/10231206.html