Android Touch Event Duration

How to determine the duration of an Android 2.1 touch event? I would like to answer only if the region was pressed within 5 seconds?

+6
android touch
source share
3 answers

You can try mixing MotionEvent and Runnable / Handler to achieve this.

Code example:

 private final Handler handler = new Handler(); private final Runnable runnable = new Runnable() { public void run() { checkGlobalVariable(); } }; // Other init stuff etc... @Override public void onTouchEvent(MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN) { // Execute your Runnable after 5000 milliseconds = 5 seconds. handler.postDelayed(runnable, 5000); mBooleanIsPressed = true; } if(event.getAction() == MotionEvent.ACTION_UP) { if(mBooleanIsPressed) { mBooleanIsPressed = false; handler.removeCallbacks(runnable); } } } 

Now you only need to check if mBooleanIsPressed true in the checkGlobalVariable() function.

One of the ideas that I came up with when I wrote this was to use simple timestamps (like System.currentTimeMillis() ) to determine the duration between MotionEvent.ACTION_DOWN and MotionEvent.ACTION_UP .

+12
source share
 long eventDuration = event.getEventTime() - event.getDownTime(); 
+21
source share

In this case, you cannot use unix timestamps. Android offers its own time dimension.

 long eventDuration = android.os.SystemClock.elapsedRealtime() - event.getDownTime(); 
+8
source share

All Articles