Last active
December 18, 2015 12:59
-
-
Save kf4x/5787111 to your computer and use it in GitHub Desktop.
checking for back button
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * first press the if statement will be executed and thread will run | |
| * | |
| * second press the else statement will be executed waking the sleep | |
| * key will NOT be 1 therefore calling else and finish | |
| */ | |
| private int timesPressed =0; | |
| @Override | |
| public boolean onKeyDown(int keyCode, KeyEvent event) { | |
| // if the back button is pressed | |
| Thread time = new Thread(); | |
| if(keyCode == KeyEvent.KEYCODE_BACK) | |
| { | |
| timesPressed++; //increment on every back button pressed | |
| //on first press start timer(sleep thread) and wait for key press | |
| if(timesPressed == 1) | |
| { | |
| Toast.makeText( | |
| getBaseContext(), | |
| "Wait, you didn't save! Press again to exit.", | |
| Toast.LENGTH_SHORT) | |
| .show(); | |
| time = new Thread(){ | |
| public void run(){ | |
| try { | |
| synchronized(this){ | |
| // Wait given period of time or exit on touch | |
| wait(2500); | |
| //if the key is still 1 then the user has not clicked back button | |
| if(timesPressed == 1){ | |
| timesPressed = 0; //reset for next press | |
| } | |
| //else times pressed will be more than 1 as the (thread woken) will resume @ line 142 | |
| else{ | |
| //finish activity | |
| finish(); | |
| } | |
| } | |
| } | |
| catch(InterruptedException ex){ | |
| ex.printStackTrace(); | |
| } | |
| } | |
| }; | |
| time.start(); | |
| return false; | |
| } | |
| //if key pressed wake thread | |
| else { | |
| //wake thread from sleep | |
| synchronized(time){ | |
| time.notifyAll(); | |
| } | |
| } | |
| } | |
| return super.onKeyDown(keyCode, event); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment