The example in this article describes how the Android implementation long presses the back key to exit the application. Share to everyone for your reference. The specific analysis is as follows:
One of the most recent applications on Android is how to implement a long press back key to exit the application. Find a lot of information on the Internet, found that almost no such implementation, most of the processing is to double-click the back key to exit the application. A reference to double-click the back key to exit the application code, online mainstream of a method is the following method, to achieve relatively simple:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18 |
@Override public boolean onKeyDown (int keycode, keyevent event) {if (keycode = = Keyevent.keycode_back) {if (System.curr Enttimemillis ()-Mexittime) >) {mhelperutils.showtoast (Mcontext, r.string.exit_content); mexittime = System.currenttimemillis (); else {finish ();} return true; Return Super.onkeydown (KeyCode, event); } |
From the above code can be seen, the use of the idea is two consecutive clicks on the back key time interval within 2s, it is considered to be double click, and then quit the program.
Therefore, from the above ideas, my initial idea is that you can rewrite the OnKeyDown method and the OnKeyUp method, calculate the interval between the two methods, if greater than 2s, it is considered to be a long press, thereby exiting the program, otherwise, perform the original response of the back key. In this way:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The |
|
However, this enables the long press the back key to exit the program, but when the back key is not long, the Click Back is invalid, looking for a lot of Android button event distribution and processing mechanism information, or do not know why (there is time to study later). Then consider a different way of thinking to deal with, consider rewriting the activity of the Dispatchkeyevent method.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The |
|
Finally, by rewriting the Dispatchkeyevent method to achieve a long press the back key to exit the program, and did not block the original not long press the back key function.
I hope this article will help you with your Android program.