I'm working with Heart Rate sensor on Samsung S6. In order access this sensor, starting from SDK Version > 23, BODY_SENSORS permission must be granted by the user https://stackoverflow.com/a/32636039/8204927 So far I've done the following
Added BODY_SENSORS permission in Manifest
Since targeted SDK Version is 23, first I check if BODY_SENSORS permission is granted to the Application, and if not, display Prompt asking user to grant the permission
Once user grants the permission I access the HeartRateSensor in the following way
SensorManager sensorManager = ((SensorManager)getSystemService(SENSOR_SERVICE));
Sensor heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE); sensorManager.registerListener(this, heartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
And it all works fine, I'm getting bpm readings as expected.
However, when I move this logic to another Activity I'm getting heartRateSensor == null, even though BODY_SENSORS has been granted in the same way as described above. What I discovered is that Android's SystemSensorManager has cached all the available Sensor Type in mSensorListByType list before the BODY_SENSORS permission has been granted, and that list isn't refreshed after granting permission.
By debugging I've discovered that second Activity overrides onResume
@Override
protected void onResume() {
super.onResume();
...
}
and that super.onResume(); calls
public List<Sensor> getSensorList(int type) {
// cache the returned lists the first time
...
}
of the SensorManager class, which populates mSensorListByType, and that list is not updated until the app restarts.
Is there any way to force SensorManager to update this list after the BODY_SENSOR permission is granted in run time, or I will have to asked the user to grant the BODY_SENSOR permission before any Activity that overrides onResume is started?