Oct 10, 2013

[android] How to bring app in background to foreground

First, you should get the list of active apps like this.
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasklist =am.getRunningTasks(10);
// Number of tasks you want to get

Then, you will have the active app list in  tasklist.  
moveTaskToFront () function will bring the app to foreground.
if(!tasks.isEmpty()) 
{
      int nSize = 
tasklist.size();
      for(int i = 0; i >= nSize;  i++) 
     {
            RunningTaskInfo taskinfo = tasklist.get(i);
           if(taskinfo.topActivity.getPackageName().equals("name of the package")) 
         {
                 
am.moveTaskToFront(taskinfo.id, 0);
         }
     }
}

Finally, add permissions to the manifest.

<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.REORDER_TASKS" />

5 comments:

  1. Thanks, this helped me a lot with my app, been all around Stackoverflow and couldn't find this info!

    ReplyDelete
  2. Thanks a lot! This works great!

    ReplyDelete
  3. If you change the >= to < it works great! Thank you!

    ReplyDelete
  4. very usefull. thnanks

    ReplyDelete
  5. I am using this as a backdoor in my xamarin android app to access them in Xamarin UI test. My app goes to background when user launches the device phone from a screen and is unable to come back to the app Is it possible to use the code for this scenario?

    ReplyDelete