Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current visible activity to user

Tags:

android

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

like image 518
Dalvinder Singh Avatar asked Jan 19 '23 02:01

Dalvinder Singh


1 Answers

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.

like image 151
A. Abiri Avatar answered Feb 05 '23 03:02

A. Abiri