在非活动类中获取当前活动上下文

时间:2013-04-23 09:59:46

标签: android-activity android-context

我在android中有一个没有的应用程序。的活动。现在我需要非活动类中当前正在运行的活动的上下文。我怎么能得到它。

1 个答案:

答案 0 :(得分:17)

您可以使用Application类:

public class MyApplication extends Application {
private static Context context;
private static Activity activity;

public void onCreate() {
    super.onCreate();
    MyApplication.context = getApplicationContext();
}

public synchronized static Context getAppContext() {
    return MyApplication.context;
}

/**
 * setCurrentActivity(null) in onPause() on each activity 
 * setCurrentActivity(this) in onResume() on each activity
 * 
 */

public static void setCurrentActivity(Activity currentActivity) {
    activity = currentActivity;
}

public static Activity currentActivity() {
    return activity;
}

}