How to control Activity flow - Back button versus Home button

后端 未结 4 1436
眼角桃花
眼角桃花 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:30

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

    0 讨论(0)
  • 2021-01-01 06:35

    On main activity add:

    android:launchMode="singleTask" android:clearTaskOnLaunch="true"

    On the others add:

    android:finishOnTaskLaunch="true"
    

    This way it will kill off any activity when returning to the app after being in background.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-01-01 06:42

    @RMS2 the answer that you suggested.. will that provide back functionality? I also faced similar problem so instead of overriding onpause and on resume, I have overriden onUserLeaveHint() method. In this way my application knows when user is pressing home button and finish the activity.

    0 讨论(0)
提交回复
热议问题