如果我做这样的事情:
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();
}
}