Activity pressed 2 times to exit

Source: Internet
Author: User

First look at the difference between onbackpressed and onkeydown.

There are two ways to get the button's events on Android

1. Direct access to the button press event, this method is compatible with Android 1.0 to Android 2.1 is also the general method, directly rewrite the activity of the OnKeyDown method, the code is as follows:

@Override
public boolean onKeyDown (int keycode, keyevent event) {
if (keycode = = Keyevent.keycode_back) {//pressed if is back and not duplicated
Toast.maketext (Ml78.this, "Back Key Test", 1). Show ();
return true;
}

Return Super.onkeydown (KeyCode, event);
}

For Android 2.0, there is a new method, for the activity can be separately get back key press event, directly rewrite the onbackpressed method, the code is as follows

@Override
public void onbackpressed () {
Here's the logic code, people Note: This method is only available for 2.0 or newer SDK
Return
}

1 now implementation to root activity press 2 This return key implementation exits

Private Static BooleanIssysexit =false; @Override Public voidonbackpressed () {//TODO auto-generated Method Stub        if(!issysexit) {Issysexit=true; Densityutil.showtoast ( This, "Press again to exit"); Timer Timer=NewTimer (); Timer.schedule (NewTimerTask () {@Override Public voidrun () {//TODO auto-generated Method StubIssysexit =false; }            }, 2000); }Else{finish (); }    }

2 Override the Back button in root activity to respond to an event, and when the back button is pressed, the activity is retired to the background

@Override Public BooleanOnKeyDown (intKeyCode, KeyEvent event) {        //TODO auto-generated Method Stub//when you press the Back button, the activity is back to the background.        if(KeyCode = =keyevent.keycode_back) {Movetasktoback (true); return true; }                return Super. OnKeyDown (KeyCode, event); }

Activity pressed 2 times to exit

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.