1. 程式人生 > >反射獲取頂層activity例項物件

反射獲取頂層activity例項物件

private void reflectActivity() {



try {
String actName = topAct(application);// com.example.calledjar.MainActivity
Class clz = application.getClass().forName(
"android.app.ActivityThread");
Method meth = clz.getMethod("currentActivityThread");
Object currentActivityThread = meth.invoke(null);
Field f = clz.getDeclaredField("mActivities");
f.setAccessible(true);
ArrayMap obj = (ArrayMap) f.get(currentActivityThread);
Log.e(tag, "______reflectActivity____");
for (Object key : obj.keySet()) {
Object activityRecord = obj.get(key);
Field actField = activityRecord.getClass().getDeclaredField(
"activity");
actField.setAccessible(true);
Object activity = actField.get(activityRecord);
System.out.println(activity);
Activity act1 = (Activity) activity;


String act1N = act1.getClass().toString();// class
// com.example.calledjar.MainActivity
String act1Name = act1N.substring(6);// class
// com.example.calledjar.MainActivity


if (actName.equals(act1Name)) {
act = act1;
Log.e(tag, "______reflectActivity____" + act.toString());
return;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


private String topAct(Application application2) {

ActivityManager am = (ActivityManager) application2
.getSystemService("activity");
ComponentName cn = am.getRunningTasks(30).get(0).topActivity;


return cn.getClassName();


}