ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • How to bring background activity to foreground
    플밍/Android 2013. 12. 4. 04:31


    How to bring background activity to front


    There are tons of questions on this, but not an answer worked out for me. 


    I tried

          - setting intent's flag (most articles describes this)

          - Android's native platform code for Recent App Launcher

          - ActivityManager#moveTaskToFront


    The results were all bad - it always created ANOTHER NEW TASK instead of just bringing existing one to front. 


    Finally! I found the solution! Ah, this is especially great when the activity you want to pick up is NOT yours - and you can't modify its manifest file.


    I believe this is the most reasonable approach in that it doesn't touch the intent itself and uses the original one in tact. Therefore, you don't have to worry about creating intent object.


    Questions and suggestions are always welcome! 




    - Key element : baseIntent of RecentTaskInfo


    private void launchApp(final String packageName) { final RecentTaskInfo runningAppInfo = getRecentTaskInfo(packageName); // If already running, just bring it to foreground if (runningAppInfo != null){ startActivity(runningAppInfo.baseIntent); // Otherwise, start new task } else { startActivity(getPackageManager().getLaunchIntentForPackage(packageName)); } } private RecentTaskInfo getRecentTaskInfo(final String packageName) { final ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); try { // 10 : # of tasks you want to take a look at final List<RecentTaskInfo> infoList = manager.getRecentTasks(10, 0); for (RecentTaskInfo info : infoList) { if (info.baseIntent.getComponent().getPackageName().equals(packageName)) { return info; } } } catch (NullPointerException e) {} return null; }




Designed by Tistory.