SensorEventListener doesn't get unregistered with unregisterListener() method

jacek picture jacek · Aug 3, 2011 · Viewed 9.6k times · Source

I have very simple Android app: in activity I have a button and I start/stop the OrientationListener. However, after unregistering it, in ddms I can still see the thread android.hardware.SensorManager$SensorThread] (Running).

The registration code:

sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
if (sensors.size() > 0)
{
    sensor = sensors.get(0);
    running = sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_FASTEST);
}

and unregistration:

try
{
    if (sensorManager != null && sensorEventListener != null)
    {
        sensorManager.unregisterListener(sensorEventListener,sensor);
        running = false;
    }
}
catch (Exception e)
{
    Log.w(TAG, e.getMessage());
}

The unregisterListener() method does get executed, however it doesn't kill the sensors thread very often, which keeps running and draining the battery. After few hours my app is listed with 20-30% battery drain. How is that possible? How can I make sure, that the sensor gets unregistered? I don't get any exceptions nor any errors in the logcat. I tried running the listener in the Service - same thing.

Answer

CvR picture CvR · Oct 14, 2012

You don't show enough code to tell for sure, but perhaps your test

if (sensorManager != null && sensorEventListener != null)

simply is not accurate. That is, sensorManager or sensorEventListener may be null when you are still registered as listening.