2015-11-04 99 views
0

我在做,有一個計時器的應用程序。我想在10秒鐘後登錄logcat。計時器在20秒完成一項不同的任務。這裏是我的嘗試:計時器記錄問題?

enter image description here

這裏是代碼:

public class TwentySeconds extends Service { 

MediaPlayer mp; 

final String TAG = "MyCountdown"; 

CountDownTimer cdt; 

@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    Log.v(TAG, "In start command"); 

    cdt = new CountDownTimer(20000, 1000) { 

     @Override 
     public void onTick(long millisUntilFinished) { 
      long timeRemaining = 20000 - millisUntilFinished; 
      if(timeRemaining % 1000 == 0){ 
       Log.v(TAG, "Time remaining" +(timeRemaining % 1000) + " seconds left"); 
      } 
     } 
     @Override 
     public void onFinish() { 
      Log.v(TAG, "Finished"); 

      Intent intent = new Intent(TwentySeconds.this,GameOver.class); 
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
      Log.v(TAG, "About to start activity"); 
      startActivity(intent); 
     } 
    }; 
    cdt.start(); 
    return START_STICKY; 
} 
@Override 
public void onDestroy() { 
    super.onDestroy(); 
} 
} 

的代碼邏輯似乎很大,但由於某些原因,它沒有顯示。非常感謝您的時間,請讓我知道。

{Rich} 
+0

設置剩餘時間滴答?並打印timeRemaining mod 1000作爲剩餘時間?它將永遠爲0 –

+0

@RandykaYudhistira它應該是10,對吧? 1000%1000 = 0? –

+0

是的。 1000%1000 = 0 –

回答

1

CountDownTimer不是100%精確的計時器,所以你不應該試圖做這樣的精確計算,因爲它會失敗的99%的時間。

也許只是做:

millisUntilFinished/1000 

爲您的時間間隔爲1秒。

試試這個:

@Override 
    public void onTick(long millisUntilFinished) { 
      long timeRemaining = 20000 - millisUntilFinished; 
      Log.v(TAG, "Time remaining " + (timeRemaining/1000) + " seconds left"); 
    } 
+0

我應該使用什麼? –

+0

你可能更好地使用一些值的範圍,而不是精確的。 –

+0

我得到:不相容類型:從布爾到長 –