问题
I have the following situation:
- Activity A starts activity B
- User presses Home button & starts another app
- 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