Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

java - SensorEventListener doesn't get unregistered with unregisterListener() method

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In my case, to solve this problem I needed to correct the context I was using to get SensorManager. I was inside a Service, and I needed to get the SensorManager this way:

SensorManager sensorManager = (SensorManager) getApplicationContext().getSystemService(SENSOR_SERVICE);

So, just certify if you are getting the SensorManager the correct way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...