19

Android newbee 在这里,我有一些我想在我的 android 应用程序第一次启动时运行的代码。它检查本地数据库的版本,如果当前版本过时,则下载新版本。我一直坚持在我的第一个活动的 oncreate 中,很确定必须有一个更好的地方来放置它。有什么推荐的地方我可以把它放在启动时会被调用一次的地方吗?

4

2 回答 2

38

You can write a custom Application class (extend from android.app.Application). Override onCreate to specify what happens when the application is started:

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        // Do something here.
    }
}

You'll then need to register your custom class in the manifest file:

<application ... android:name="fully.qualified.MyApplication">

Edit:

In response to David Cesarino, I disagree with the purpose of the Application class. If you rely on the Activity's onCreate, then what's to stop it from becoming the same huge class of miscellaneous purposes... if you need something to happen when the application starts, you have to write that code somewhere; and the Activity would probably become more cluttered because you have to perform Activity specific logic in it as well. If you're worried about clutter, then separate the logic into other classes and call them from the Application. Using the SharedPreferences to determine whether or not the logic should execute seems like more of a work-around to a problem that's already been solved.

Dianne Hackborn seems to be referring to data, not logic, in which I totally agree. Static variables are much better than Application level variables... better scoping and type safety make maintainability/readability much easier.

于 2012-07-21T17:13:16.417 回答
4

首先,看一下Activity 生命周期

回答您的问题,您可以将代码放入任何这些“启动”方法中,具体取决于您想要做什么,最重要的是,您想要触发它时。对于你所问的,onCreate是合理的地方。

我一直坚持在我的第一个活动的 oncreate 中,很确定必须有一个更好的地方来放置它。

那为什么呢?任何代码都有一个入口点,对吧?在 Android 活动中它恰好是onCreate(再次,请参阅上面的链接以获取完整的详细信息)。除了事件处理(即对主调用序列之外发生的事件的响应)之外,您还可以在onCreate.

如果您担心该方法变得庞大,那么这是另一个问题。我说,更好地抽象你的代码。为了检查初步的东西,人们通常在启动应用程序的主要活动之前提供一个“加载”活动。

编辑:

这是对drumboog 提议的后续行动,因为我的评论开始变得复杂到“只是评论”。

就个人而言,我会避免扩展Application类的唯一原因是早期执行代码,更重要的是优先级不那么明智的代码(版本控制数据库)。该类Application主要用作在'ies之间保持状态Activity的简单方法,而不是“做所有事情”的方法。简而言之,我觉得这Application门课经常被滥用。

对于您想要的,您可以在Activity onCreate. 这降低了复杂性,因为我看到人们一直在填充Application,直到它变成一大类杂项代码。这是维护的禁忌,本身就有逻辑问题。

Besides, if you truly want another solution, completely disassociated with the UI, you should think about implementing a Service instead (but I don't think it's necessary for just that).

Both of those concerns were previously addressed by Dianne Hackborn (or what I got from her message).

于 2012-07-21T17:07:44.863 回答