是否在启动Activity之前扩展Application如何运行代码?

时间:2016-08-17 20:10:19

标签: android android-application-class

如果我这样做:

public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //init something else here if you want
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        //terminate something else here if you want
    }

}

并在Manifest文件中包含此类的名称,如下所示:

<application
        android:name="com.packagename.MyApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

这是否有效地为我们提供了在应用运行之前和之后运行我们想要的任何代码的方法?

修改:如果我进入onCreate()语句,我会在代码中看到这一点:

/**
     * Called when the application is starting, before any activity, service,
     * or receiver objects (excluding content providers) have been created.
     * Implementations should be as quick as possible (for example using 
     * lazy initialization of state) since the time spent in this function
     * directly impacts the performance of starting the first activity,
     * service, or receiver in a process.
     * If you override this method, be sure to call super.onCreate().
     */
    @CallSuper
    public void onCreate() {
    }

    /**
     * This method is for use in emulated process environments.  It will
     * never be called on a production Android device, where processes are
     * removed by simply killing them; no user code (including this callback)
     * is executed when doing so.
     */
    @CallSuper
    public void onTerminate() {
    }

编辑2:我还可以将应用程序上下文保存为全局静态变量:

public class MyApp extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        MyApp.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApp.context;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}

2 个答案:

答案 0 :(得分:2)

不是在整个Application生命周期之前和之后,例如所有正在运行Activity s,Service和其他上下文生物...如果它们当前都不可见/正在运行Android系统可能始终从内存中删除Application(用户也是)。< / p>

如果您正在寻找一种在屏幕外运行某些代码/没有任何UI的方法,请查看Service课程或其他延迟警报基础方法。

你不能依赖于Application类的子类,因为你甚至不知道它何时被OS杀死&#34;自动&#34;。

答案 1 :(得分:1)

是。 扩展Application类

的主要原因
  • 是否要将所有初始化设置为单例 整个应用程序和组件中使用。
  • 有一些静态变量 跨组件使用

参考:Logic why we should use