android - 扩展应用程序是如何在启动 Activity 之前运行代码的?

标签 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();
    }
}

最佳答案

不是之前和之后,而是整个 Application 生命周期,例如所有正在运行的 ActivityService 和其他上下文生物...如果它们当前都不可见/正在运行的 Android 系统可能会始终删除您的 Application 来自内存(用户也是)。

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

你不能依赖子类化 Application 类,因为你甚至不知道它什么时候被操作系统“自动”杀死。

关于android - 扩展应用程序是如何在启动 Activity 之前运行代码的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39005433/

相关文章:

android - 如何为我的 Espresso Activity 测试提供自定义应用程序类?

java - 在Android中动态创建应用程序类

android - 当应用程序启动依赖于网络调用时,如何处理 Android 中的进程重新创建?

android - 是否可以从 Application 类调用 Activity 类中的方法?

android - 如何获取正在运行的服务并从 Activity 中手动停止它?

统计记录的 SQL 查询

android - fragment 中的操作栏项目单击处理程序

java - 在 Java 后端和 Android 应用程序之间共享 POJO

android - 用户通知 - 如何从 GCM 恢复丢失的 notification_id?