测量Android中两个MotionEvents之间的时间间隔

我是Android编程新手,所以我要求你帮忙解决我的问题。 我正在尝试以秒/毫秒为单位测量MouseEvent.ACTION_DOWN和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 

我的问题实际上是秒variables不显示我想要什么,我甚至不知道它的测量是否正确。对于上面的例子持续时间是16545(???!?!?),但它应该在1 -3秒。我应该怎样做,以两秒或两秒之间的时间在几秒或几毫秒内正确测量,或者我的例子中我错了什么? 谢谢 !

Solutions Collecting From Web of "测量Android中两个MotionEvents之间的时间间隔"

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

MotionEvent有一个时间戳。 使用getEventTime()来访问它。

实际上,由于不能保证MotionEvent会立即传送到您的代码,因此此时间戳比从System.getCurrentTimeMillis()获得的时间更准确。

这里是@CvR描述的解决scheme:

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