2

I have the following situation:

  1. Activity A starts activity B
  2. User presses Home button & starts another app
  3. After a while, I want activity B to bring itself (not create new instance) to foreground

How can I do this?

I tried using intents with FLAG_ACTIVITY_REORDER_TO_FRONT, FLAG_FROM_BACKGROUND and set B's launch mode as singleTask, singleInstance but none of them work.

1 Answers1

5

Just use this method in your activity as per your situation. it will work.

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("Your app pckg name") > -1) {                     
                      activityManager.moveTaskToFront(recentTasks.get(i).id, ActivityManager.MOVE_TASK_WITH_HOME);

               }
        }
    }
}

Also you need to add below permission in manifest.

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />
Ams
  • 51
  • 1
  • 3