0

I want to check which activity is on the front, from a class that is no activity (that's just another class that does some actions for me, but not bounded with any activity).

How can I check from this class which activity is actually showing on the screen?

ConcurrentHashMap
  • 4,998
  • 7
  • 44
  • 53
user1302569
  • 7,131
  • 13
  • 46
  • 66

2 Answers2

7

You can use ActivityManager to get this. Following is the sample code:

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);


 // get the info from the currently running task
 List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);

 Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());

 ComponentName componentInfo = taskInfo.get(0).topActivity;
 String packageName = componentInfo.getPackageName();

You will need the following permission on your manifest:

uses-permission android:name="android.permission.GET_TASKS"

Source

Praful Bhatnagar
  • 7,425
  • 2
  • 36
  • 44
0

Another way is to create in a custom Application object a member called "Activity lastActivityShown" and in all onCreate of all Activities you can getApplication().setLastActivityShown(this) in this way you dont need permissions. You can also create a BaseActivity that have this logic and get all Activities extends this.

PaNaVTEC
  • 2,505
  • 1
  • 23
  • 36