I have an app that connects to an URL every X seconds in an onPostExecute of a library that I had done. When I close the app or go back with the back button, it must stop with an override of the onPause()
method on the main activity class.
I want to control this with my own library to facilitate the creation of class for new developers, but if I override it on the library onPause()
method, it continues making connections.
There's a way to do these on my library?
Here my code on the main class:
@Override
public void onPause() {
super.onPause();
myLib.stopResource();
myLib.flagRefresh = false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
myLib.stopResource();
myLib.flagRefresh = false;
super.onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
You should use onStop()
instead of onPause()
, which is called whenever the activity is not shown on screen but is still running, i.e. when the screen goes black. Instead of overwriting onKeyDown()
it is better to use onBackPressed()
method, however if you place your current code of onPause()
inside onStop()
it would not be required to overwrite it.
The only way I see it is to derive a new class from Activity supporting your library. But this approach will run into a permutational explosion. Any specialist standard activity needs a MyLib-variant too. (ListActivity, FragmentActivity, and so on)
class MyLibActivity extends Activity {
@Override
public void onPause() ..
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)..
}
So it's probably the best to offer just a support for the pure activity.
来源:https://stackoverflow.com/questions/9784942/onpause-android