user1302569
user1302569

Reputation: 7191

How to check which activity is showing on screen

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?

Upvotes: 0

Views: 1323

Answers (2)

PaNaVTEC
PaNaVTEC

Reputation: 2503

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.

Upvotes: 0

Praful Bhatnagar
Praful Bhatnagar

Reputation: 7435

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

Upvotes: 7

Related Questions