Android - Background activity bring itself to foreground

大憨熊 提交于 2020-01-23 13:26:04

问题


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:


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" />


来源:https://stackoverflow.com/questions/20306350/android-background-activity-bring-itself-to-foreground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!