Here's a tip:
long start = System.currentTimeMillis(); // start time (NOT 0. KEEP READING) // your code long finish = System.currentTimeMillis(); // finish time (NOT THE DURATION) // the duration is the difference between the start and finish time (look up currentTimeMillis() if you want to know why) System.out.println("Your code took " + (finish - start) " milliseconds");
However, I have already created a stopwatch class (methods to simulate a stopwatch). Using my class (download here), it's much easier.
Put the following code in your activity class that you want to have to press back twice in a short period of time for the activity to finish.
Stopwatch stopwatch = new Stopwatch(); @Override public void onBackPressed() { if (stopwatch.getMilliseconds() < 500 && stopwatch.isGoing()) { finish(); } else { stopwatch.reset(); stopwatch.start(); } }
The only thing you may want to change is stopwatch.getMilliseconds() < 500
. That means that the user has to press back twice within half a second for the activity to close.
You may want to have it within an entire second, so something like this: stopwatch.getMilliseconds() < 1000
or stopwatch.getSeconds() < 1
Created: March 27, 2014
Completed in full by: Michael Yaworski