据我所知,没有本地方法可以检查您是否已经注册了侦听器。我不会太担心这个检查,因为这个检查已经由 Android 完成,所以如果你已经注册了监听器,Android 不会添加相同的监听器两次:
@SuppressWarnings("deprecation")
private boolean registerLegacyListener(int legacyType, int type,
SensorListener listener, int sensors, int rate)
{
if (listener == null) {
return false;
}
boolean result = false;
// Are we activating this legacy sensor?
if ((sensors & legacyType) != 0) {
// if so, find a suitable Sensor
Sensor sensor = getDefaultSensor(type);
if (sensor != null) {
// If we don't already have one, create a LegacyListener
// to wrap this listener and process the events as
// they are expected by legacy apps.
LegacyListener legacyListener = null;
synchronized (mLegacyListenersMap) {
legacyListener = mLegacyListenersMap.get(listener);
if (legacyListener == null) {
// we didn't find a LegacyListener for this client,
// create one, and put it in our list.
legacyListener = new LegacyListener(listener);
mLegacyListenersMap.put(listener, legacyListener);
}
}
// register this legacy sensor with this legacy listener
legacyListener.registerSensor(legacyType);
// and finally, register the legacy listener with the new apis
result = registerListener(legacyListener, sensor, rate);
}
}
return result;
}
因此,您可以根据需要多次调用 registerListener,它只会被添加一次:)
这同样适用于注销逻辑