How to exit the Android program by pressing the back key

Source: Internet
Author: User

The main purpose is to enable the program to exit when you press the back key.

Implementation ideas:
1. The event is triggered when the back key event is captured.

Copy codeThe Code is as follows: @ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
// If you press BACK, there are no duplicates at the same time
If (keyCode = KeyEvent. KEYCODE_BACK & event. getRepeatCount () = 0 ){
// DO SOMETHING
....
}
Return true;
}

2. Exit the program when the backend key is pressed.
There are also two ways: exit the program directly or exit to the main screen.

1) Two Ways to exit the program:

Android. OS. Process. killProcess (android. OS. Process. myPid ());

System. exit (0 );

I tried these two methods, But the strange thing is that in the 1.5 simulator, the program was indeed killed, but Android immediately restarted the program.

In addition, there is another method that is friendly and can release resources. I think it is feasible, that is, it is a little troublesome to implement it. You need to exit step by step and rewrite the onResume () method:

Copy codeThe Code is as follows: @ Override
Protected void onResume (){
Super. onResume ();
If (mExiting ){
Finish ();
}
}

2) exit to the home screen (recommended)
This is relatively simple. You can create an Intent for the home screen.Copy codeThe Code is as follows: Intent home = new Intent (Intent. ACTION_MAIN );
Home. setFlags (Intent. FLAG_ACTIVITY_CLEAR_TOP );
Home. addCategory (Intent. CATEGORY_HOME );
StartActivity (home );

Related Article

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.