Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, how to bring a Task to the foreground?

My question:

How can I launch a new Activity in its own Task while using the following rules.

1) If the Activity already exists as a root of a another Task (within the same application) then bring the Task to the foreground. I don't want another instance of the Activity to be created. I just want the Task that it is the root of to come to the foreground and the top Activity of the Task to be displayed.

Note: it will only be the root of one Task at a time and it will only exist as the root of the Task and nowhere else.

2) If the Activity doesn't exist then create this Activity in its own Task.

Why I'm trying to achieve this? I created four bottoms at the bottom of my Activities that should behave like tabs. So if I press the second "tab" I want the Activity that is associated with that tab to be displayed. But if it already exist and is on the bottom of its own Task then I would like that Task to be displayed with whatever Activity that is currently on the top of the Task.

What have I tried so far? I've searched stackOverflow and couldn't find a similar question. I read http://developer.android.com/guide/topics/fundamentals/tasks-and-back-stack.html and http://blog.akquinet.de/2010/04/15/android-activites-and-tasks-series-intent-flags/

I think I need to use either FLAG_ACTIVITY_NEW_TASK and/or affinities but not sure. Looking for a hand please.

Thanks, Bradley4

like image 278
bradley4 Avatar asked Aug 02 '11 22:08

bradley4


1 Answers

I was able to solve this for Android version >= Honeycomb:

@TargetApi(11)
protected void moveToFront() {
    if (Build.VERSION.SDK_INT >= 11) { // honeycomb
        final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

        for (int i = 0; i < recentTasks.size(); i++) 
        {
               Log.d("Executed app", "Application executed : " 
                       +recentTasks.get(i).baseActivity.toShortString()
                       + "\t\t ID: "+recentTasks.get(i).id+"");  
               // bring to front                
               if (recentTasks.get(i).baseActivity.toShortString().indexOf("yourproject") > -1) {                     
                  activityManager.moveTaskToFront(recentTasks.get(i).id, ActivityManager.MOVE_TASK_WITH_HOME);
               }
        }
    }
}

you also need to add these to your manifest:

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />
like image 158
droideckar Avatar answered Sep 22 '22 13:09

droideckar