2012-03-19 39 views
7

我是Android編程的新手,所以我要求您在我的問題中提供幫助。 我正在嘗試以秒/毫秒爲單位測量MouseEvent.ACTION_DOWN和MouseEvent.ACTION_UP之間的時間量。在Android中測量兩個MotionEvents之間的運行時間

@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 

我的問題在於事實秒變量不顯示我的 想,我甚至不知道它的測量correctly.For上述 例如持續時間爲16545(???!但它應該在 之間1-3秒。我該怎麼做才能在幾秒鐘內正確測量或者兩個MotionEvents之間的時間爲012毫秒,或者我的例子中 的錯誤是什麼?謝謝 !

回答

11
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 
    } 
} 
+0

謝謝你,看着你的代碼,我發現我的錯:可變長的啓動應該聲明的全局,在我的功能不是本地的,非常感謝你! – Matey 2012-03-19 02:51:19

+3

您應該使用'System.nanoTime()'而不是'System.currentTimeMillis()'。請閱讀javadoc的兩個函數,據說'currentTimeMillis()'不應該用於測量時間間隔,因爲它可能會在運行時調整。 – keaukraine 2013-03-05 13:36:32

+0

感謝keaukraine,使用納米時間()適應的變化 – 2013-08-16 07:32:26

8

一個MotionEvent有一個時間戳。使用getEventTime()來訪問它。

事實上,由於不能保證MotionEvent會立即傳送到您的代碼,因此此時間戳比您從System.getCurrentTimeMillis()獲得的任何時間都更準確。

+1

+1這與'android.os.SystemClock.uptimeMillis()'一起使用實際上是找到向下和向上事件之間的時間的正確解決方案。 – 2014-01-12 20:45:48

0

這裏是@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 
    } 
} 
相關問題