I would like to start a timer that begins when a button is first pressed and ends when it is released (basically I want to measure how long a button is held down). I'll be using the System.nanoTime() method at both of those times, then subtract the initial number from the final one to get a measurement for the time elapsed while the button was held down.
(If you have any suggestions for using something other than nanoTime() or some other way of measuring how long a button is held down, I'm open to those as well.)
Thanks! Andy
In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so.
When Home button is pressed, onStop method is called in your activity. So what you may do is to add finish(); in onStop method to destroy your activity. Eventually onDestroy method will be raised to confirm that your activity is finished.
When you press the Home button on the device, the onPause method will be called. If the device thinks that it needs more memory it might call onStop to let your application shut down.
Pressing the Home key allows the user to start a new Task, by showing the launcher. All active Tasks (and therefore Activities incl. your "Air Control" example) will call their onPause() method.
Use OnTouchListener instead of OnClickListener:
// this goes somewhere in your class: long lastDown; long lastDuration; ... // this goes wherever you setup your button listener: button.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN) { lastDown = System.currentTimeMillis(); } else if (event.getAction() == MotionEvent.ACTION_UP) { lastDuration = System.currentTimeMillis() - lastDown; } return true; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With