Unregister SensorManager not working

In my application, I use the ambient light and proximity sensor to detect the functionality of the phone from my pocket, and then unregister the SensorManager when their detection is complete. But even when the processor’s use of the application shows only 1-2 seconds, battery usage always shows my application as not. 1 on the list, which is troubling.

I used SensorManager.unRegisterListener and also set SensorManager = null, but the situation remains the same.

I read that due to some kind of error, the sensors are not registered unregistered. Any good way to handle sensors properly?

Travel Guide Pls. Omkar Gaisas

Updated using sample code from application -

@Override protected void onPause() { super.onPause(); unHookReceiver(); } private void unHookReceiver() { if (r != null) { unregisterReceiver(r); if(GetProximityPreference("EnableReceiveByProximity")) { mySensorManager.unregisterListener(proximitySensorEventListener); mySensorManager.unregisterListener(lightSensorEventListener); mySensorManager = null; FileUtils.appendLog(FileUtils.GetCurrentDateTime() + " Power Consumption Log End"); FileUtils.appendLog("------------------------------------------------"); } r = null; } } 

I also set sensorManager = null according to a single sentence from a single post in stackpverflow, but even this does not help. Despite calling the wipe code, battery usage is still very large. The application itself should not use a large battery, since it is a very simple application with one broadcast receiver and one action, but as part of the action, I call the Light and Proximity sensors, and I doubt that they cause a surge in battery consumption. Not sure why.

Any help is very noticeable.

+2
source share
3 answers

I was able to solve this by comparing correctly when the listeners were registered and when they were unregistered. Perhaps, initially the listeners did not receive properly unregistered in all conditions of the call (incoming call, outgoing call, missed call, etc.), therefore, even when the activity is closed, the listeners still listened to the events, therefore they consumed energy unnecessarily.

0
source
 mSensorManager.registerListener(YourListener.this, mSensorManager .getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_NORMAL); 

take this to register your Listener ... then your unregisterListener

+1
source

Just put this register in the main handler, then it works. but I do not know why.

 Handler mainHandler = new Handler(Looper.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { if (mSensorManager != null) { mSensorManager.registerListener(sensorEventListener, mProximity, SensorManager.SENSOR_DELAY_NORMAL); } } }); 
+1
source

Source: https://habr.com/ru/post/1206947/


All Articles