Back-key processing in Android

Source: Internet
Author: User

Back key is the back button on the phone, the general software does not capture relevant information may cause your program to be switched to the background, and return to the desktop embarrassing situation, on Android there are two ways to get the button event.

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 BooleanOnKeyDown (intKeyCode, KeyEvent event) {    if(KeyCode = = Keyevent.keycode_back && event.getrepeatcount () = = 0) {//if it's back, it's not duplicated.//add your own processing logicToast.maketext (testbackactivity. This, "Monitoring System Return key", Toast.length_long). Show (); return true; }    return Super. OnKeyDown (KeyCode, event);} 

2. Overriding the Onbackpressed method

And for Android 2.0 started a new method, for the activity can be separately get back key press event, directly rewrite the onbackpressed method, code as follows:

@Override  Public void  ///super.onbackpressed (); This sentence must be called off, or else to call the default back processing mode //  here to handle the logic code, Note: This method is only available for 2.0 or newer SDK}

Eg: double-exit the application:

 /*** Return key two hits, first click Time*/   Private LongExittime = 0; @Override Public voidonbackpressed () {//super.onbackpressed (); This sentence must be dropped, or else to call the default back processing mode//Here's the logic code, People Note: This method is only available for 2.0 or newer SDK            if((System.currenttimemillis ()-Exittime) > 2000) {Toast.maketext (Getapplicationcontext (),"Press one more time to exit the program", Toast.length_short). Show (); Exittime=System.currenttimemillis (); } Else{finish (); }}

Back-key processing in Android

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.