In Android development, the exit key function and menu cannot be used

Source: Internet
Author: User

There is no better way now. You can only determine whether the user can click and quit consecutively within 2 seconds. If yes, the user will quit. If not, the user will give up listening. The Code is as follows:

Long exitTime = 0;


Public boolean onKeyDown (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_BACK
& Event. getAction () = KeyEvent. ACTION_DOWN ){
If (System. currentTimeMillis ()-exitTime)> 2000 ){
Toast. makeText (getApplicationContext (), "exit the program again ",
Toast. LENGTH_SHORT). show ();
ExitTime = System. currentTimeMillis ();
} Else {
Finish ();
System. exit (0 );
}
Return true;
}
Return super. onKeyDown (keyCode, event );
}


In addition, This sentence may be added, and the menu will show the problem of clicking no pop-up window. This problem is easy to be solved!

The Code is as follows:

You must have written this method.

@ Override
Public boolean onMenuItemSelected (int featureId, MenuItem item ){
// TODO Auto-generated method stub
Return super. onMenuItemSelected (featureId, item );
}

Modify it to this way,

Public boolean onOptionsItemSelected (MenuItem item ){

Return true;

}

Add the following code to avoid errors.

Public boolean onKeyUp (int keyCode, KeyEvent event ){
If (keyCode = KeyEvent. KEYCODE_MENU ){
This. getLocalActivityManager (). getCurrentActivity ()
. OpenOptionsMenu ();
}
Return true;
}

Finished!

Author's "step-by-step column"
 

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.