当 Android 应用程序启动并存在时运行代码
在我的应用程序中,我需要在应用程序关闭(暂停)时调用代码,然后在应用程序再次启动(恢复)时再次运行代码。例如,我调用一个 Web 服务,该服务在应用程序启动或退出时同步数据。这在 iOS 中很容易,因为有中央应用程序恢复和挂起方法。
我了解 Activity 中的 OnPause 和 OnResume,但是,是否有一个集中的方法来处理这个问题?用户可以将应用程序留在 Activity3 上,稍后再回来,或者在另一个屏幕中,等等。我不想在每个 Activity 的 OnPause 和 OnResume 中都使用相同的代码来处理“应用程序”启动和关闭代码例程。
有什么建议吗?
谢谢。
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 the 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建一个通用 Activity,它仅以某种方式处理 onResume() 和 onPause(),然后使每个 Activity 都从该 Activity 扩展,而不是直接从 Activity 扩展。
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.
我会考虑对 Activty 进行子类化,让每个活动都扩展它,并在其中任何一个活动暂停或恢复时执行您需要的操作。
您可以在 Application 类中使用一些静态成员,您的新活动库将使用这些静态成员来跟踪状态或存储您需要的任何内容。
此外,Application 类有一个 onCreate() 方法,该方法将在每次启动应用程序时运行。但是,应用程序没有暂停或恢复。
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.
创建一个由所有其他活动扩展的主活动并覆盖 onPause 和 onResume。
但是,如果您想扩展另一个 Activity 类(例如 ListActivity),您将面临问题。
另一种方法是创建一个新类来扩展应用程序并重写其 onCreate 并创建一个充当 onPause 的静态方法并由每个活动手动调用它
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