问题
I'm writing a game for Android and want to be able to use the accelerometer for input.
I see two ways of getting a sensor, one way is to use the first element of SensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER)
and the other is SensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
.
The getDefaultSensor doc says it could return a "composite" sensor, so if I want a "raw" sensor I should use getSensorList
.
Any idea what the difference between a composite or raw sensor is? Does this even apply to the accelerometer? Anyone have experience with devices that contain multiple or composite accelerometers? (Or some other sensor?)
回答1:
Google's documentation is way ahead of their implementation here. I browsed through the code repository (which seems to be 2.3.1-ish source) and found:
public Sensor getDefaultSensor(int type) {
// TODO: need to be smarter, for now, just return the 1st sensor
List<Sensor> l = getSensorList(type);
return l.isEmpty() ? null : l.get(0);
}
So there is no real difference (and I don't think they can really add one later) between the sensors returned from getDefaultSensor()
and from getSensorList()
.
回答2:
An update: They have updated the getDefaultSensor method in Lollipop, and there now is a difference:
public Sensor getDefaultSensor(int type) {
// TODO: need to be smarter, for now, just return the 1st sensor
List<Sensor> l = getSensorList(type);
boolean wakeUpSensor = false;
// For the following sensor types, return a wake-up sensor. These types are by default
// defined as wake-up sensors. For the rest of the SDK defined sensor types return a
// non_wake-up version.
if (type == Sensor.TYPE_PROXIMITY || type == Sensor.TYPE_SIGNIFICANT_MOTION ||
type == Sensor.TYPE_TILT_DETECTOR || type == Sensor.TYPE_WAKE_GESTURE ||
type == Sensor.TYPE_GLANCE_GESTURE || type == Sensor.TYPE_PICK_UP_GESTURE) {
wakeUpSensor = true;
}
for (Sensor sensor : l) {
if (sensor.isWakeUpSensor() == wakeUpSensor) return sensor;
}
return null;
}
So if there are multiple sensors available for the specified type, getDefaultSensor will return a non-wakeup version (unless the default type is one of those 6 above actually defined as a wakeup sensor)
By the way, Sensor.TYPE_TILT_DETECTOR, Sensor.TYPE_WAKE_GESTURE, Sensor.TYPE_GLANCE_GESTURE and Sensor.TYPE_PICK_UP_GESTURE are hidden in the SDK, as they are intended to be used only for the system UI. There's more details on them in the Sensor.java source
来源:https://stackoverflow.com/questions/7565822/getsensorlist-vs-getdefaultsensor-in-android-sensormanager