2

Is there any way i can detect for how long a button is press?? I want to capture the time for which a button is press and act accordingly. So if a user kept pressing the button for 5 sec i want to detect that 5 sec on android.

Please let me know

Thanks Pranay

Pranay Airan
  • 1,855
  • 6
  • 28
  • 52

4 Answers4

3

Use following to determine the touch duration.You can use that in an if statement: event.getEventTime() - event.getDownTime() > 5000 It calculates in ms, which means that for your 5 sec you need this number to be 5000

DON'T USE: android.os.SystemClock.elapsedRealtime()-event.getDownTime() It might work on the simulator, but it won't work on the device! Don't ask me how I know it ;)

D3us3x
  • 51
  • 5
2
    private long timeElapsed = 0L; //make this a global variable

    //tvTouches could be a TextView or Button or other views
    tvTouches.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    timeElapsed = event.getDownTime();
                    Log.d("setOnTouchListener", "ACTION_DOWN at>>>" + event.getDownTime());
                    break;
                case MotionEvent.ACTION_UP:
                    timeElapsed = event.getEventTime() - timeElapsed;
                    Log.d("setOnTouchListener", "ACTION_UP at>>>" + event.getEventTime());
                    Log.d("setOnTouchListener", "Period of time the view is pressed>>>" + timeElapsed);
                    Toast.makeText(getApplicationContext(), "Period of time the view is pressed in milliseconds>>>" + timeElapsed, Toast.LENGTH_SHORT).show();
                    timeElapsed = 0L;
                    //TODO do something when a certain period of time has passed
                    break;
                default:
                    break;
            }
            return true;
        }
    });
s-hunter
  • 24,172
  • 16
  • 88
  • 130
2

Give the button a View.OnTouchListener. The onTouch method you'll implement will give you access to a MotionEvent. Then, using getFlags(), you'll know when the user starts pressing the button (ACTION_DOWN) and when he stops (ACTION_UP). Simply record the system time when these occur (or as suggested in another answer, getDownTime() will give the time you need, but only when you have the ACTION_UP flag).

Pang
  • 9,564
  • 146
  • 81
  • 122
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124
1

Register a OnTouchListener on the Button. Then in the listener use the MotionEvent:

http://developer.android.com/reference/android/view/MotionEvent.html

Then use the getDownTime() method of the Event:

http://developer.android.com/reference/android/view/MotionEvent.html#getDownTime%28%29