Android - How to get last foreground activity on android?

1.1k Views Asked by At

I have an app which open different activity on different situation from response of server. Let i have two activity Activity A & Activity B. A or B can't be start at the same time. Let assume A activity is called to start and at the same time B is also called to start. If A is started first , B hide it and start on top of view making A in background. How can i check if A is already started from inside Activity B ??

tILL NOW WHAT I HAVE TRIED:

ActivityManager m = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfoList = m.getRunningTasks(10);
    Iterator<ActivityManager.RunningTaskInfo> itr = runningTaskInfoList.iterator();
    while (itr.hasNext()) {
        ActivityManager.RunningTaskInfo runningTaskInfo = (ActivityManager.RunningTaskInfo) itr.next();
        int id = runningTaskInfo.id;
        CharSequence desc = runningTaskInfo.description;
        int numOfActivities = runningTaskInfo.numActivities;
        String topActivity = runningTaskInfo.topActivity.getShortClassName();
        Constants.debugLog(TAG, "checkActivityStack desc: " + desc + " numOfActivities: " + numOfActivities + " topActivity: " + topActivity);
    }

========================= aNOTHER ONE FROM STACK

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

    int sizeStack =  am.getRunningTasks(5).size();

    for(int i = 0;i < sizeStack;i++){
        ComponentName cn = am.getRunningTasks(2).get(i).topActivity;
        Constants.debugLog(TAG, "checkActivityStack "+cn.getClassName());
    }
2

There are 2 best solutions below

2
On

I would probably make an public field, the code would look something like this:

// A
public static boolean started = false;

@Override
public void onStart() {
    super.onStart();
    started = true;
}

@Override
public void onStop() {
    super.onStop():
    started = false;
}

And a check would look like this:

// B
if (A.started) {
    // Abort starting
}
3
On

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());

you need to use permission for android.permission.GET_TASKS Hope this helps