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

前端 未结 2 1809
后悔当初
后悔当初 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<? extends Activity> 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.

    0 讨论(0)
  • 2020-12-10 19:48

    Ok, I was able to get this to work by adding a static global variable in my main activity (activity_A). In onCreate I set isRunning = true, and onDestory = false. Then in my IntentReceiver class I check the isRunning to determine which activity to start:

                :
        if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
            if (GlobalVariables.isRunning) {
                activityClass = BringToFront.class;
            } else {
                activityClass = activity_A.class;
            }
        } else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            activityClass = activity_A.class;
        }
                :
    
    0 讨论(0)
提交回复
热议问题