在编写android应用的时候一般跟界面相关的都离不开activity,很多时候我们需要在纯java环境中使用activity对象,一般情况下我们都是靠参数传递去使用。现在我们可以使用纯java代码来获取当前系统中的activity对象,有了activity对象我们就可以做很多想做的事情,比如监听改activity的生命周期,给改activity界面添加浮动view等等。废话少说看下面方法:
public static Activity getGlobleActivity() throws ClassNotFoundException, IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException{ Class 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; } } return null; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-11 13:48:16