views:

106

answers:

2

I have 3 activities in my app:

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.

+1  A: 

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;
}
RMS2
+1  A: 

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

Quartz
But does that allow me to press "Back" from Activity3 to get back to Activity2? Or will it just always go back to Activity1?
RMS2