Android 应用内获取当前运行Activity

  • 官方解决方案registerActivityLifecycleCallbacks

类似的

/**
 * 监听Application中Activity生命周期,获取顶部Activity
 */
public class WindowLifecycle implements Application.ActivityLifecycleCallbacks, Closeable {

    private Activity currentActivity;

    public WindowLifecycle(Context context) {
        if (context == null) {
            return;
        }
        if (context instanceof Application) {
            ((Application) context).registerActivityLifecycleCallbacks(this);
        } else {
            ((Application) context.getApplicationContext()).registerActivityLifecycleCallbacks(this);
        }
    }

    /**
     * 获取当前运行的activity
     */
    public Activity getCurrentActivity() {
        Log.i("ActivityLifecycle", "getCurrentActivity");
        return this.currentActivity;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {
        this.currentActivity = activity;
    }

    @Override
    public void onActivityPaused(Activity activity) {
        this.currentActivity = null;
    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }


    @Override
    public void close() throws IOException {
        if (currentActivity != null) {
            currentActivity = null;
        }
    }

    /**
     * 销毁资源
     */
    public void destroyed() {
        if (currentActivity != null) {
            currentActivity = null;
        }
    }
}
复制代码

通过getCurrentActivity()来获取当前运行activity

  • 反射解决方案
/**
   * 获取当前运行的activity
   */
  public static Activity getTopActivity() {
      Log.i("activity", "[getTopActivity]");
      try {
          Class activityThreadClass = Class.forName("android.app.ActivityThread");
          Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
          Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
          activitiesField.setAccessible(true);
          //16~18 HashMap
          //19~27 ArrayMap
          Map activities;
          if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
              activities = (HashMap) activitiesField.get(activityThread);
          } else {
              activities = (ArrayMap) activitiesField.get(activityThread);
          }
          if (activities.size() < 1) {
              return null;
          }
          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 (Exception e) {
          e.printStackTrace();
      }
      return null;
  }
复制代码

优先使用ActivityLifecycleCallbacks,在lifecycle中获取为空时,再通过反射进行二次获取(lifecycle极地概率获取不到,可能原因是国产rom的activity生命周期出现异常导致)

你可能感兴趣的:(Android 应用内获取当前运行Activity)