从应用程序上下文中获取 Android 个应用程序
Get Android application from application context
我可以访问应用程序上下文,但不能访问应用程序。我想获取该应用程序(这样我就可以获得所有 运行 活动),但找不到这样做的方法。是否存在从应用程序上下文中获取应用程序的现有 API,或者我必须为此重写 getApplicationContext?
不,没有现成的 API。但是,您可以获取应用程序上下文并将其转换为 Application 对象,或者扩展应用程序 class 并使其成为单例,以便您可以从任何地方获取它的实例。
public class MyApplication extends Application {
private static MyApplication singleton;
// Returns the application instance
public static MyApplication getInstance() {
return singleton;
}
public final void onCreate() {
super.onCreate();
singleton = this;
}
}
我可以访问应用程序上下文,但不能访问应用程序。我想获取该应用程序(这样我就可以获得所有 运行 活动),但找不到这样做的方法。是否存在从应用程序上下文中获取应用程序的现有 API,或者我必须为此重写 getApplicationContext?
不,没有现成的 API。但是,您可以获取应用程序上下文并将其转换为 Application 对象,或者扩展应用程序 class 并使其成为单例,以便您可以从任何地方获取它的实例。
public class MyApplication extends Application {
private static MyApplication singleton;
// Returns the application instance
public static MyApplication getInstance() {
return singleton;
}
public final void onCreate() {
super.onCreate();
singleton = this;
}
}