Dalvinder Singh
Dalvinder Singh

Reputation: 2149

Get current visible activity to user

I want to get the foreground activity running. And I am able to get this information by using activity manager by using following code.

activityManager = (ActivityManager) FWCommon.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
runningTaskInfoList = activityManager.getRunningTasks(1);
componentName = runningTaskInfoList.get(0).topActivity;

Suppose I have two activities A and B and i call this above code from onResume() of both activities A and B.

Following is the problem

  1. When activity A starts above code gives me topActivity = A
  2. Then I move from activity A to B and above code gives me topActivity = B
  3. Then i press Back to move back from activity B to A and above code again gives me topActivity = B instead of A.

Thx Dalvin

Upvotes: 4

Views: 7624

Answers (1)

A. Abiri
A. Abiri

Reputation: 10810

Try using getRunningAppProcesses() to get a list of RunningAppProcessInfo. Then go through each RunningAppProcessInfo and check if it is in the foreground by doing this:

List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo process : processes)
{
    // Take a look at the IMPORTANCE_VISIBLE property as well in the link provided at the bottom
    if (process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
    {
        // Put code here
    }
}

Click here and here for more information.

Upvotes: 9

Related Questions