63 lines
2.1 KiB
Plaintext
63 lines
2.1 KiB
Plaintext
The `android.hardware.SensorManager#getDefaultSensor` offers two types of Motion Sensors:
|
|
|
|
- `TYPE_ROTATION_VECTOR:` a combination of the gyroscope, accelerometer, and magnetometer.
|
|
- `TYPE_GEOMAGNETIC_ROTATION_VECTOR:` a combination of the accelerometer and magnetometer.
|
|
|
|
== Why is this an issue?
|
|
|
|
The battery life is a major concern for mobile devices and choosing the right Sensor is very important to reduce the power usage and extend the battery life.
|
|
|
|
It is recommended, for reducing the power usage, to use `TYPE_GEOMAGNETIC_ROTATION_VECTOR` for _background tasks_, _long-running tasks_
|
|
and other tasks not requiring accurate motion detection.
|
|
|
|
The rule reports an issue when `android.hardware.SensorManager#getDefaultSensor` uses `TYPE_ROTATION_VECTOR` instead of `TYPE_GEOMAGNETIC_ROTATION_VECTOR`.
|
|
|
|
== How to fix it
|
|
|
|
Replace `TYPE_ROTATION_VECTOR` with `TYPE_GEOMAGNETIC_ROTATION_VECTOR` when retrieving the Motion Sensor.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public class BackGroundActivity extends Activity {
|
|
|
|
private Sensor motionSensor;
|
|
|
|
@Override
|
|
protected void onCreate(Bundle savedInstanceState) {
|
|
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
|
|
motionSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); // Noncompliant
|
|
// ..
|
|
}
|
|
//..
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
public class BackGroundActivity extends Activity {
|
|
|
|
private Sensor motionSensor;
|
|
|
|
@Override
|
|
protected void onCreate(Bundle savedInstanceState) {
|
|
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
|
|
motionSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR); // Compliant
|
|
// ..
|
|
}
|
|
//..
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://source.android.com/docs/core/interaction/sensors/power-use[Android - Low Power Sensors]
|
|
|
|
* https://developer.android.com/develop/sensors-and-location/sensors/sensors_motion[Android - Motion Sensors] |