Measure elapsed time between two MotionEvents in Android

I am new to Android programming, so I ask you to help with my problem. I am trying to measure in seconds / milliseconds the time between MouseEvent.ACTION_DOWN and MouseEvent.ACTION_UP.

@Override public boolean onTouchEvent(MotionEvent event) { long start=0; if (event.getAction() == MotionEvent.ACTION_DOWN) { // manage down press start=System.nanoTime();//START System.out.println("START"); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { // manage move System.out.println(event.getRawX()+","+event.getRawY()); } else { // manage up long finish=System.nanoTime()//FINISH long seconds = (finish-start) / 1000000000;//for seconds Toast.makeText(this, "FINISH, duration: "+seconds, Toast.LENGTH_SHORT).show(); System.out.println("FINISH, duration: "+seconds); } return true; } Logcat: 03-19 04:04:27.140: I/System.out(4348): START 03-19 04:04:27.160: I/System.out(4348): 517.0,280.0 03-19 04:04:27.190: I/System.out(4348): 517.0,280.0 03-19 04:04:27.200: I/System.out(4348): 517.0,280.0 03-19 04:04:27.220: I/System.out(4348): 517.0,280.0 03-19 04:04:27.250: I/System.out(4348): 517.0,280.0 03-19 04:04:27.260: I/System.out(4348): 517.0,280.0 03-19 04:04:27.300: I/System.out(4348): 517.0,280.0 03-19 04:04:27.310: I/System.out(4348): 517.0,280.0 03-19 04:04:27.330: I/System.out(4348): FINISH, duration: 16545 

My problem is that the seconds variable does not show what I want, I don’t even know if its measurement is correct. An example of a duration was 16545 (?!?!?), but it should have been between 1-3 seconds. What should I do to correctly measure seconds or milliseconds the time between two MotionEvents or what am I mistaken in my example? Thanks!

+7
source share
4 answers
 long startTime; public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) startTime = System.nanoTime(); else if (event.getAction() == MotionEvent.ACTION_UP) { long elapseTime = System.nanoTime() - startTime; //do whatever u want with elapseTime now, its in nanoseconds } } 
+11
source

A MotionEvent has a timestamp. Use getEventTime() to access it.

In fact, since there is no guarantee that MotionEvent will be delivered immediately to your code, this timestamp is more accurate than ever when you get from System.getCurrentTimeMillis() .

+8
source

Here is the solution described by @CvR:

 private long startTimeInMilliSec; @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) startTimeInMilliSec = event.getEventTime(); else if (event.getAction() == MotionEvent.ACTION_UP) { long elapsedTime = event.getEventTime() - startTimeInMilliSec; //do whatever u want with elapsedTime now, its in milliseconds } } 
0
source

Each event also has getDownTime() . So when you got MotionEvent.ACTION_UP you can just use

event.getDownTime() - event.getEventTime()

calculate elapsed time.

0
source

All Articles