Measure elapsed time between two MotionEvents in Android

流过昼夜 提交于 2019-11-28 13:35:03
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
    }
}

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

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

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 
    } 
} 

Each event also have getDownTime() method. So when you received MotionEvent.ACTION_UP you can simple use

event.getDownTime() - event.getEventTime()

to calculate elapsed time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!