(机器人)如何做某事在App"启动"?机器人、如何做、QUOT、App

2023-09-04 11:56:32 作者:小猪佩奇我配你

我知道Android的活动模式是什么,我通常认为是一个应用程序有点不同。

I know Android's Activity model is a bit different from what I usually consider to be an "app".

我想要做的事(在这种情况下,检查一些通知的服务器上,如果有的话告诉他们)时,我的应用程序启​​动。什么是做到这一点的好办法?

I want to do something (in this case, check some notifications on a server and show them if available) when my app is "launched". What is a good way to accomplish this?

我可能不想做一个活动的OnCreate,因为每个活动可以创建任意次数 - 在code会被调用往往比必要

I likely don't want to do it in an activity's OnCreate, since each activity can be created any number of times - the code would get called more often than necessary.

该应用程序还拥有多个入口点 - 我会重复在每个活动检查

The app also has multiple entry points - would I have to duplicate the check in each activity?

我在想什么做的是建立Application对象这里面code,伴随着一个标志,用于跟踪是否它已经被称为 - 从每个活动的onCreate()只是把它

What I'm thinking of doing is setting up this code inside the Application object, along with a flag that tracks whether it's already been called - and just call it from each Activity's onCreate().

有没有更好或更正确的方式做到这一点?

Is there a better or more "proper" way to do this?

推荐答案

在右键,Android的批准方式以做到这一点:

创建你自己的 android.app.Application 类 重写的onCreate 方法 在的Andr​​oidManifest.xml ,修改安卓名称应用程序的属性元素的类的名称 现在,只要您的应用程序启​​动(开始你activites中的任何一个,第一次,没有其他情况还活着)的onCreate 将被调用。 Create your own android.app.Application class Override the onCreate method In the AndroidManifest.xml, change the android:name attribute of the application element to the name of your class Now, whenever your app is "started" (any one of your activites is started for the first time and no other instances are alive) onCreate will be called.

您也可以找到 onTerminate 的方法是有用的。

You may also find the onTerminate method useful.