Android "Press again to quit program" specific implementation

Source: Internet
Author: User

Many of the ways to quit programs in Android apps are when you click on the Back button, it pops up a message "press again to exit", this and when we just need to press the Back button, the program exits, sometimes the time interval is 3 seconds or other time interval, today I will briefly say the implementation principle.

In fact, the implementation is relatively simple, we need to cover a method in the activity: public void onbackpressed (); This method is called when the return key is clicked, overwriting this method after we rewrite its implementation:

<span style= "White-space:pre" ></span>private static long back_pressed = 0; @Overridepublic void Onbackpressed () {if (Back_pressed+2000>system.currenttimemillis ()) super.onbackpressed (); else {Toast.makeText ( This, "Press again to Exit", "()" Show (); back_pressed = System.currenttimemillis ();}}
We also need to define a static variable as shown in the code to record the time we clicked the button, from the code we can know, when we click on the button, we first determine whether the current back_pressed+2000 value is greater than the current system time, if greater than, then we exit the program, If not greater than, that is, after we clicked the return button, in the interval of 2 seconds we did not click the second time, so the program does not exit, but record the time of the click, for the next click to make a judgment preparation.

Android "Press again to quit program" specific implementation

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.