开发者

Run code when Android app starts and exists

开发者 https://www.devze.com 2023-03-07 20:53 出处:网络
In my app I need to call code whenever the app closes (pauses) and then run code again whenever the app starts again (resumes).For example, I call a web service that syncs the data whenever the app st

In my app I need to call code whenever the app closes (pauses) and then run code again whenever the app starts again (resumes). For example, I call a web service that syncs the data whenever the app starts or exits. This is easy in iOS because of the central app resume and suspend methods.

I understand th开发者_StackOverflow社区e OnPause and OnResume in the Activity, however, is there a central way to handle this? The user could leave the app on Activity3 and come back later, or be in another screen, etc. I'd hate to have to have the same code in every Activity's OnPause and OnResume to handle the "app" startup and shutdown code routines.

Any suggestions?

Thank you.


You could make a common Activity which just handles onResume() and onPause() in a certain way and then make every Activity extend from that one instead of Activity directly.


I would consider subclassing Activty, have each of your activities extend that and just do what you need to when any of them pause or resume.

You could use some static members in an Application class that your new activity base uses to track state or store whatever you need.

Also, Application class has an onCreate() method which will run each time the application is started. There is no pause or resume for Application, however.


Creating a main Activity that is extended by all your other activities and override the onPause and onResume.

But the problem you will face if you want to extend another Activity class such as a ListActivity.

Another approach is to create a new class that extends application and override its onCreate and create a static method that acts as onPause and manually call it by each of your activities

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号