[英]Get Android application from application context
I have access to application context but not to application. 我可以访问应用程序上下文,但不能访问应用程序。 I want to get the application (so I can get all running activities), but couldn't find a way to do so. 我想要获取该应用程序(以便可以获取所有正在运行的活动),但是找不到找到该方法的方法。 Is there an existing API to get application from application context or I will have to override getApplicationContext for that? 是否有现有的API可以从应用程序上下文中获取应用程序,否则我将不得不重写getApplicationContext?
No, there's no such API out of the box. 不,没有现成的API。 However, you can either get application context and cast it to Application object, or Extend Application class, and make it a singleton so you can grab an instance of it from everywhere. 但是,您既可以获取应用程序上下文并将其强制转换为Application对象,也可以将Extend Application类扩展为单个实例,以便可以从任何地方获取它的实例。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.