gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:16:00 26 4
gpt4 key购买 nike

如果我这样做:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com