Activity exits twice and activityexits twice.

Source: Internet
Author: User

Activity exits twice and activityexits twice.

Let's take a look at the differences between onBackPressed and onKeyDown.

There are two ways to get the button event on Android

1. directly obtain the button and press the event. This method is compatible with Android 1.0 to Android 2.1 and is also a common method. You can directly rewrite the onKeyDown method of the Activity. The Code is as follows:

@ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK) {// if you press BACK, there are no duplicates
Toast. makeText (ml78.this, "Back key test", 1). show ();
Return true;
}

Return super. onKeyDown (keyCode, event );
}

There is a new method for Android 2.0 at the beginning. For Activity, you can independently obtain the Back key press event and directly rewrite the onBackPressed method. The Code is as follows:

@ Override
Public void onBackPressed (){
// Process the logic code here. Note that this method is only applicable to sdk 2.0 or later versions.
Return;
}

1. Now, press 2 on the Root Activity to exit.

 

Private static boolean isSysExit = false; @ Override public void onBackPressed () {// TODO Auto-generated method stub if (! IsSysExit) {isSysExit = true; DensityUtil. showToast (this, "exit once again"); Timer timer = new Timer (); timer. schedule (new TimerTask () {@ Override public void run () {// TODO Auto-generated method stub isSysExit = false ;}, 2000 );} else {finish ();}}

 

2. Rewrite the back button in the root Activity to respond to the event. When you press the back button, move the Activity back to the background.

@ Override public boolean onKeyDown (int keyCode, KeyEvent event) {// TODO Auto-generated method stub // when you press the return key, move the Activity back to the background if (keyCode = KeyEvent. KEYCODE_BACK) {moveTaskToBack (true); return true;} return super. onKeyDown (keyCode, event );}

 

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.