简体   繁体   中英

control hardware back button

In my application, I want to control the hardware back button. That means if in my app there are four or five activity. Now suppose I move from one activity to another,

like this "start 1->2->3->4->2->4->1 end" Now in my case when I press the hardware back button it reaches 1st page in similar manner,

"end 1<-2<-3<-4<-2<-4<-1 start"

so my question is that what should I do so that when I press the hardware back button

on 1st page exit on 2nd page reach 1st page (pressed back button again) exit.

etc...

on 4th page reach 3rd (back button) 2nd (back) 1st (back) exit.

There is a method onBackPressed() . You can override that method in your activity to achieve this.

@Override
public void onBackPressed()
{
    Intent go=new Intent(this.class,your_desired_activity.class);
    startActivity(go);
    super.onBackPressed();  
}

launch actvity withActivity flag clear top so that every activity on top of stack will be get cleared .

so in case if you launch your activity 2 with clear top after this sequence start ->1<-2<-3<-4<- 2

your stack will be start->1->2

similary if you lauch your activity 1 with clear top flag after this sequence start 1->2->3->4->2->4- 1

your stack will be start->1

you can read more about back stack here http://developer.android.com/guide/components/tasks-and-back-stack.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM