要插入$ C $下应用程序的启动? [英] Where to insert code for application startup?

查看:178
本文介绍了要插入$ C $下应用程序的启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的Andr​​oid newbee,我有,我想,当我的Andr​​oid应用程序第一次启动时运行一些code。它检查本地数据库的版本和下载新的版本,如果当前版本已过时。我一直坚持它在我的第一个活动的OnCreate,pretty的肯定,必须有一个更好的地方来存放这一点。什么地方的,我可以把它放在任何建议它会被调用一次,在启动?

Android newbee here, I have some code that I want to run when my android app first starts up. It checks the version of the local database and downloads a new version if the current version is out of date. I have been sticking it in the oncreate of my first activity, pretty sure there has to be a better place to put this. Any recommendations of somewhere I can put it where it will get called once on startup?

推荐答案

您可以编写自定义应用程序类(从android.app.Application扩展)。覆盖的onCreate 指定应用程序启动时会发生什么:

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">

编辑:

在回应大卫Cesarino,我不同意应用程序类的目的。如果你依赖于活动的onCreate ,那么什么是成为同一个庞大的类杂项目的停止...如果你需要的东西在应用程序启动的时候发生,你必须在某处写code;和活动可能会变得更加混乱,因为你必须在它执行活动特殊逻辑。如果你担心的混乱,再分出业务逻辑,其他类,并从应用程序调用它们。使用共享preferences 确定逻辑应该执行与否似乎更多的是一种变通,以包括已经解决的问题。

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.

戴安娜Hackborn似乎指的是数据,而不是逻辑,在此我完全同意。静态变量是不是应用程序级的变量要好得多......更好的范围和类型安全化妆可维护性/可读性强多了。

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.

这篇关于要插入$ C $下应用程序的启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆