Bring task to front on android.intent.action.USER_PRESENT

前端 未结 2 2010
后悔当初
后悔当初 2020-12-10 19:11

BACKGROUND
I have a task (i.e. app) with multiple activities.

QUESTION
How do I bring a task to the front w/o re-ordering

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 19:47

    Here's a slightly hackish implementation that works for me:

    • Create a simple BringToFront activity that simply finish() itself on its onCreate():

      public class BringToFront extends Activity {
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              finish();
          }
      
      }
      
    • In your BroadcastReceiver, start the BringToFront activity above instead of your activity_A if the action is USER_PRESENT:

      @Override
      public void onReceive(Context context, Intent intent) {
          Class activityClass = activity_A.class;
      
          if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
              activityClass = BringToFront.class;
          }
      
          Intent i = new Intent(context, activityClass);
          i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(i);
      }
      

    This works because the BringToFront activity has the same taskAffinity as your activity_A and starting it will make the system bring the existing task to the foreground. The BringToFront activity then immediately exit, bringing the last activity on your task (activity_B in your scenario) to the front.

    It's worth noting that on API level 11 (Honeycomb), a moveTaskToFront() method is added to the system's ActivityManager service that might probably be the better way to achieve what you want.

提交回复
热议问题