Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when button pressed and released on android

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

like image 330
Andy Thompson Avatar asked Aug 15 '12 03:08

Andy Thompson


People also ask

How can I tell if my Android back button is pressed?

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.

What happens to activity when home button is pressed?

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.

Which method is called when home button is pressed in Android?

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.

Which method gets called when Home button pressed?

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.


1 Answers

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;      }   }); 
like image 198
Nick Avatar answered Sep 20 '22 11:09

Nick