When my app activity goes in background with Home button or Back button, some Listener codes like requestLocationUpdates or threads are still running, Why?
-
1You should unregister listeners in the `onPause()` override for Activities. For more information on the general subject you're asking about, read this: http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon – Daniel Nugent May 17 '15 at 03:51
-
As Daniel said, you'll have to understand the android Activity lifecycle. More info on that here: http://developer.android.com/training/basics/activity-lifecycle/index.html – Mauker May 17 '15 at 04:16
3 Answers
About the issue with Threads:
Have always a loop in 5he run method which you control via a boolean like isRunning e.g. and an inner loop which is controlled by !isPaused for exmpl
If you want to "pause" the thread so just set isPaused to true and if you want to kill it set isRunning to false (of isPaused to true)
In the running loop let the thread sleep for 100ms, so that he wakes every 100+ms up to check if it is still paused

- 1,272
- 12
- 26
You can implement these two callback method in the class (where Activity is extended) and write the code to handle the execution when the activity hides and when back button (or some other button) is pressed
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
/*code to handle when back button is pressed*/
}
else if (keyCode == KeyEvent.KEYCODE_HOME) {
/*code to handle when HOME sbutton is pressed*/
}
return false;
}
@Override
protected void onPause() {
/*code to handle when activity goes in background and becomes inactive*/
super.onPause();
}

- 3,322
- 25
- 30
Add code to pause location when onpause method is called. here is what i am using. locationManager
is the object of LocationManager
@Override
protected void onPause() {
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
super.onPause();
}

- 1,237
- 1
- 16
- 29