Android: How to switch to Activity that has alread

2019-09-21 07:55发布

问题:

I'm new to Android programming. What I want to do is to swith to an another activity that has already been created. Suppose I started Activity B and move from Activity A to Activity B, and then I pressed back button and move back to Activity A. Now I want to switch to Activity B when a countdown timer is done.

ActivityA.java

  private void startTimer() {
        ...
        @Override
        public void onFinish() {
            // force the user to move on to Activity B
            // if the user haven't started Activity B, just start it
            if (!mHasActivityBStarted) {
                Intent intent =
                        new Intent(ActivityA.this, ActivityB.class);
                startActivity(intent);
            } else {
                // how can I switch to ActivityB that has been created?
            }
        }
    }.start();
}

How can I do it?

回答1:

From Android Developer documentation

FLAG_ACTIVITY_REORDER_TO_FRONT

public static final int FLAG_ACTIVITY_REORDER_TO_FRONT

If set in an Intent passed to Context.startActivity(), this flag will cause the launched activity to be brought to the front of its task's history stack if it is already running.

For example, consider a task consisting of four activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then B will be brought to the front of the history stack, with this resulting order: A, C, D, B. This flag will be ignored if FLAG_ACTIVITY_CLEAR_TOP is also specified.

In your case, you can switch between ActivityA and ActivityB without finishing or recreating them.

Put it together.

ActivityA

// Call this method when users press a button on ActivityA to go to ActivityB.
public void goToActivityB(View view) {
    Intent intent = new Intent(this, ActivityB.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);
}

// When users press a button from ActivityB, ActivityA will be bring to front and this method will be called by Android.
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // Write your logic code here
}

ActivityB

// Call this method when users press on a button in ActivityB
public void backToActivityA(View view) {
    Intent intent = new Intent(this, ActivityA.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);
}

// When users press a button from ActivityA, ActivityB will be bring to front and this method will be called by Android.
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // Write your logic code here
}