How to know if my SensorManager has a registered Sensor

chntgomez picture chntgomez · Jan 11, 2013 · Viewed 7.5k times · Source

I'm using a sensor for my Android Application. I register the sensor with a line of code:

mySensorManager.registerListener(this, orientationSensor, SensorManager.SENSOR_DELAY_NORMAL);

I have introduced a line of code to unregister the listener so it wont be running all time:

mySensorManager.unregisterListener(this);

So far it works, but i need to register it again when the application resumes. I need to know if my sensorManager has a registered listener so I can registered again or skit it. Does something like this can be done?:

if (mySensorManager.getRegisteredListenerList == null){ registerListener() } else { .. }

Answer

Pavel Dudka picture Pavel Dudka · Jan 11, 2013

As far as I know, there is no native way to check if you have already registered listener. I would not worry too much about this check since this check is already done by Android, so if you have already registered listener, Android is not gonna add the same listener twice:

@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;
    }

So you can call registerListener as many times as you want it will only be added once:)

The same is applicable for unregister logic