我在android中有一个没有的应用程序。的活动。现在我需要非活动类中当前正在运行的活动的上下文。我怎么能得到它。
答案 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;
}
}