Android - Dynamically Get the Current Activity in Foreground

戏子无情 提交于 2019-11-27 12:14:50

I'm not sure if this is what you're looking for, but it seemed pretty straightforward. http://iamvijayakumar.blogspot.com/2011/09/get-current-activity-and-package-name.html

  ActivityManager am = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
  List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
  ComponentName componentInfo = taskInfo.get(0).topActivity;
  Log.d(WebServiceHelper.TAG, "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName()+"   Package Name :  "+componentInfo.getPackageName());

Hope this helps.

Plan A: taking your request literally

Step #1: Have the thread be managed by a service

Step #2: have the service send a message when the "even is triggered" -- LocalBroadcastManager, Square's Otto, greenrobot's EventBus, etc.

Step #3: Have each activity be set up to listen for that message when it is in the foreground

Step #4: Have the activity display the dialog upon receipt of the message


Plan B: same visual result

Step #1: Have the thread be managed by a service

Step #2: Have the service call startActivity() on a dialog-themed activity

Step #3: There is no step #3

You can achieve this using a custom broadcast receiver. You can define a broadcast receiver in your thread and write the receiver in different activities. And from your thread you can decide which activity to send broadcast.

In the receiver, you can show the dialog.

frogmanx

You may do that by extending Activity and Application and having methods that get and set the current viewed Activity reference as an Application level variable. Try this approach: How to get current foreground activity context in android?.

Use Face book's stetho package is safest and simplest way for me (and no complaints from other team members that "it's hacky we won't approve!" thing...

Just as simple as:

ActivityTracker.get().tryGetTopActivity();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!