通过反射获取当前Activity实例
Posted 月色下的独轮车
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过反射获取当前Activity实例相关的知识,希望对你有一定的参考价值。
步骤:
1、 获取ActivityThread中保存的所有的ActivityRecord
2 、从ActivityRecord中获取状态不是pause的Activity并返回,这个Activity就是当前处于活动状态的Activity
具体代码:
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实例的主要内容,如果未能解决你的问题,请参考以下文章