本人在项目开发过程中遇到需要开发一款手表应用,并且需要获取心率等生命体征信息。此处以获取心率举例记录
首先获取权限
<uses-permission android:name="android.permission.BODY_SENSORS" />
其实只是实现读取心率是比较容易的,接下来是部分代码
private SensorManager mSensorManager;private Sensor mHeartRateSensor;@Overridepublic void onCreate() {super.onCreate();//判断是否有权限,注意没有权限是取不到数据的,切记!此处没有判断用户是否点了是,所以需要自己加if (!checkPer(Manifest.permission.BODY_SENSORS)) {ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BODY_SENSORS}, 100);}mSensorManager =(((SensorManager)getSystemService(SENSOR_SERVICE)));mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);mSensorManager.registerListener(sensorEventListener, mHeartRateSensor, 3);}private boolean checkPer(String permission) {return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;}SensorEventListener sensorEventListener = new SensorEventListener() {@Overridepublic void onSensorChanged(SensorEvent sensorEvent) {Log.d(TAG, "sensor event: " + sensorEvent.accuracy + " = " + sensorEvent.values[0]);//在这里获取心率并处理 sensorEvent.values[0]; }@Overridepublic void onAccuracyChanged(Sensor sensor, int i) {}};@Overrideprotected void onDestroy() {super.onDestroy();mSensorManager.unregisterListener(sensorEventListener);}
查看手表可以获取的数据内容
List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);for (Sensor sensor : sensors) {Log.e(TAG,"sensor:[name=" + sensor.getName() + ";type="+ sensor.getType() + ";vendor="+ sensor.getVendor() + "]");}