Implementation mechanism: When the user clicks on the physical return key, the activity calls onbackpressed (), simply by copying the method in the activity
Here is the code implementation:
1 PackageCom.example.qjm3662.service_learn;2 3 ImportAndroid.content.ComponentName;4 Importandroid.content.Intent;5 Importandroid.content.ServiceConnection;6 ImportAndroid.os.IBinder;7 Importandroid.support.v7.app.AppCompatActivity;8 ImportAndroid.os.Bundle;9 ImportAndroid.view.Window;Ten ImportAndroid.widget.TimePicker; One ImportAndroid.widget.Toast; A - Public classMainactivityextendsappcompatactivity { - the //A static tag that identifies whether the user has continuously clicked the back button two times within the specified time - Static intEvent_back = 0; - @Override - protected voidonCreate (Bundle savedinstancestate) { + Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); + } A at @Override - Public voidonbackpressed () { - //If the user clicks the Back button continuously within two seconds, the default action is performed (typically ejecting the activity stack in the current activity) - if(Event_back = = 1){ - Super. onbackpressed (); -}Else{ in //user First Click, set Event_back to 1 to indicate that the user has clicked once -Event_back = 1; to //pop up the toast box to remind the user to exit the program at one click +Toast.maketext (mainactivity. This, "Press again to exit", Toast.length_short). Show (); -Timepicker Timepicker =NewTimepicker ( This); the //If the user does not click the Back button again within two seconds, the event_back is reset to 0, the user needs to re-click two times *Timepicker.postdelayed (NewRunnable () { $ @OverridePanax Notoginseng Public voidrun () { -Event_back = 0; the } +},2000); A } the } +}
Custom back key (Implementation press two return key to exit the program)