在我的静态方法中(参数只有一个字符串),我想使用Dialog(new AlertDialog.Builder(mContext)
),但是对话框需要一个活动上下文来构造。如果我不通过反射或其他方法传递外部上下文参数,如何获取当前顶级活动的对象?
public static Activity getActivity() {
Class activityThreadClass = null;
try {
activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map activities = (Map) activitiesField.get(activityThread);
for (Object activityRecord : activities.values()) {
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
if (!pausedField.getBoolean(activityRecord)) {
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
Activity activity = (Activity) activityField.get(activityRecord);
return activity;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return null;
}
我使用了这段代码,但是当我在非Activity类中调用此方法时,activities
为空。
还有其他方法吗?无法使用对话框,只要能够弹出信息就可以被用户看到。点数限制:不从参数中获取上下文。
答案 0 :(得分:2)
使用Application.ActivityLifecycleCallbacks
实施例:
class ActivityLifeCycleCallbackImpl implements Application.ActivityLifecycleCallbacks {
private Set<Activity> set = new HashSet<>();
@Override
public void onActivityStarted(Activity activity) {
set.add(activity);
}
@Override
public void onActivityStopped(Activity activity) {
set.remove(activity);
}
Activity getCurrentActivity() {
if (set.isEmpty()) {
return null;
}
return set.iterator().next();
}
}
并在您的自定义应用程序类中:
ActivityLifeCycleCallbackImpl activityLifeCycleCallback = new ActivityLifeCycleCallbackImpl();
@Override
public void onCreate() {
registerActivityLifecycleCallbacks(activityLifeCycleCallback);
}