Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control Activity flow - Back button versus Home button

I have 3 activities in my application:

Activity1 -> Activity2 -> Activity3

Inside Activity3, if the user presses Back, I would like to return to Activity2. In Activity3's onPause event, I added a finish() statement. That's probably not even necessary, but I wanted to make sure this Activity gets cleaned up. This works fine.

However, while in Activity3, if the user presses Home or starts a new app (through notification bar or some other means), I want both Activity3 and Activity2 to finish. If the user returns to this app, he should resume with Activity1.

I have figured out how to do one or the other, but I can't figure out how to handle both cases, if it's even possible. Can I trap the "Back" button in Activity3 and send a message back to Activity2 telling it not to finish()? It seems like the Activities follow the same lifecycle flow (Pause, Stop) regardless of what you do to send them to the background.

Just to answer the question of why I want this behavior, imagine that Activity1 is a login screen, Activity2 is a selection screen, and Activity3 is a content screen. If I press Back from the content page, I want to be able to make a new selection. If I exit via any other means (Home, notification bar), I want the user to be "logged out".

Thanks in advance for your help.

like image 348
RMS2 Avatar asked Nov 21 '25 16:11

RMS2


2 Answers

Once again, I have answered my own question. I'll post my solution here in case it helps someone else.

In the onPause events of both Activity2 and Activity3, I added finish(). This takes care of the case where the user presses Home or responds to a Notification Bar event while in those activities. Since these activities are both finished, if the user returns to the app, they will get Activity1 (now at the top of the stack.)

In Activity3, I added an onKeyDown trap for the "Back" key. Since Activity2 was killed when it went onPause, we have to fire off a new Activity2 from Activity3. After starting Activity2, Activity3 then finishes. Here's the code for Activity3's onKeyDown:

public boolean onKeyDown(int keyCode, KeyEvent event){
    if(keyCode == KeyEvent.KEYCODE_BACK) {
            Intent Act2Intent = new Intent(thisActivity, Activity2.class);              
            startActivity(Act2Intent);          
            finish();
            return true;
    }
    return false;
}
like image 106
RMS2 Avatar answered Nov 23 '25 07:11

RMS2


You can also give Activity1 the android:clearTaskOnLaunch attribute in your AndroidManifest.xml.

like image 43
Ross Light Avatar answered Nov 23 '25 05:11

Ross Light



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!