How to reference the current or main activity from another class

后端 未结 13 799
难免孤独
难免孤独 2021-01-30 12:39

I often find myself needing to access methods that require referencing some activity. For example, to use getWindowManager, I need to access some Activity. But ofte

13条回答
  •  -上瘾入骨i
    2021-01-30 13:02

    Just a guess since I haven't done this but it might work.

    1) Get your applicationContext by making your Android Application class a Singleton.

    2) Get your ActivityManager class from the context.

    3) Get a list of RunningTaskInfos using getRunningTasks() on the ActivityManager.

    4) Get the first RunningTaskInfo element from the list which should be the most recent task launched.

    5) Call topActivity on that RunningTaskInfo which should return you the top activity on the activity stack for that task.

    Now, this seems like a LOT more work than any of the other methods mentioned here, but you can probably encapsulate this in a static class and just call it whenever. It seems like it might be the only way to get the top activity on the stack without adding references to the activities.

提交回复
热议问题