質問

My application is a set of Activities and I have not subclassed Application. There is a static singleton class that runs a recurring timer (java.util.Timer). That timer needs to be paused when the user leaves my application.

If there were only one activity, I could pause and resume the timer onPause() and onResume() of MainActivity. How should I solve this problem in my case?

役に立ちましたか?

解決 4

I found that onDestroy and onCreate are called appropriately, so I overrode those.

Overriding onPause and onStart for all activities would be troublesome since the timer would be paused and resumed every time a new activity was launched.

他のヒント

Create a BaseActivity and pause and resume the timer in onPause and onResume. Then derive all other activities from BaseActivity.

If you have this static singelton, you could call through onPause() and onResume() from every Activity.

Put the calls into a subclass of Activity to reduce code duplication. Extend this new subclass in all your activities.

if all your activitys stay open within the application you can use this, and if the app is closed isFinishing() will be called in your onPause()

 @Override 
public void onPause() {        

        if(isFinishing()){
//code to finish() all activitys threads etc.....
}            

    super.onPause();
}

You can do multiple things:

  1. Just do nothing, when user leaves all activities your app will stop and all of your objects, even static singleton will be released from memory.

  2. Track the active activity via this singleton, and when no one is active pause the timer.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top