9

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

4

1 回答 1

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;
}

}
于 2013-05-06T09:49:41.877 回答