How to control Activity flow - Back button versus Home button

后端 未结 4 1469
眼角桃花
眼角桃花 2021-01-01 05:52

I have 3 activities in my application:

Activity1 -> Activity2 -> Activity3

Inside Activity3, if the user presses Back, I would like t

4条回答
  •  情深已故
    2021-01-01 06:41

    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;
    }
    

提交回复
热议问题