onPause() Android

ぐ巨炮叔叔 提交于 2019-12-06 12:39:07

问题


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);    
}

回答1:


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.




回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!