Search code examples
javaandroidandroid-sensorsproximitysensorauto-close

Turn off proximity sensor after closing app - Android


I made an app that reads values off of the proximity sensor and performs certain actions based off of that data. My problem is that the actions will continue to perform even when the user presses the home button and leaves the app, thus causing a drainage in the battery.

My question is how do I turn off the proximity sensor once the app is existed or simple when the home button is pressed (without the app being exited properly)

This is my first Android app. Here is how I assign the proximity sensor in my code:

    sm = (SensorManager) getSystemService(SENSOR_SERVICE);
    proxSensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);

    sm.registerListener(this,proxSensor,SensorManager.SENSOR_DELAY_NORMAL);

Thanks

EDIT To those that are wondering and don't want to look it up, I solved it by using the following:

public void onPause()
{
    super.onPause();
    sm.unregisterListener(this);
}
public void onResume()
{
    super.onResume();
    sm.registerListener(this,proxSensor,SensorManager.SENSOR_DELAY_NORMAL);
}

Solution

  • Look into the Activity method onStop(). It's called whenever the Activity is no longer visible, (app is exited or home button is pressed). It is into this method where you will put your code to stop the proximity sensor.

    See Android Activity lifecycle diagram here for more info:

    http://developer.android.com/reference/android/app/Activity.html