从应用程序上下文中获取Android应用

时间:2015-09-04 00:11:48

标签: android android-context

我可以访问应用程序上下文但不能访问应用程序。我想获得应用程序(所以我可以获得所有正在运行的活动),但是找不到这样做的方法。是否存在从应用程序上下文获取应用程序的现有API,或者我必须为此覆盖getApplicationContext?

1 个答案:

答案 0 :(得分:1)

不,没有开箱即用的API。但是,您可以获取应用程序上下文并将其强制转换为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;
        } 
    }