2014-09-12 128 views
1

我正在嘗試創建一個簡單的Tap Counter應用程序,但在移動到onFinish()之前,我在最後得到了明顯的滯後,在停止之前給予用戶一些額外的水龍頭櫃臺。Android:CountDownTimer中的onFinish()之前的延遲

這裏是MainActivity.java

package com.example.tapcounter; 

import android.os.Bundle; 
import android.os.CountDownTimer; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
import android.app.Activity; 

public class MainActivity extends Activity 
{ 
TextView time; 
TextView taps; 
Button b; 

int flag = 0; 
int count = 0, finalTap = 0; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    time = (TextView) findViewById(R.id.textView1); 
    taps = (TextView) findViewById(R.id.textView2); 
    b = (Button) findViewById(R.id.button1); 

    b.setOnClickListener(new OnClickListener() 
    { 

     @Override 
     public void onClick(View arg0) 
     { 
      if(finalTap==0) 
      { 
       if(flag==0) 
       { 
        beginTimer(); 
        flag=1; 
       } 
       updateCount(); 
      } 
     } 
    }); 
} 

private void beginTimer() 
{ 
    new CountDownTimer(10000, 1000) 
    { 

     public void onTick(long millisUntilFinished) 
     { 
      time.setText("Time: "+millisUntilFinished/1000); 
     } 

     public void onFinish() 
     { 
      time.setText("Timeout!!!"); 
      finalTap++; 
     } 
    }.start(); 
} 

private void updateCount() 
{ 
    taps.setText("Taps: " + Integer.toString(++count)); 
} 
} 

回答

0

的因素有兩個位置:

  • 第一onTick和onFinish不會發生在準確的時間 - 在你的榜樣millisUntilFinished參數將有類似的值8995等達990.

  • 你的onTick方法中的第二次計算使用整數除法 - 餘數被截斷。因此,在最後一次調用990/1000時繼續我們的示例將爲0,但onFinish將僅在約1000毫秒後調用。

0

第一次如何運行你的應用程序?我注意到當我在Debugmode中運行一個應用程序時,調試器吃掉了我移動設備性能的50%。所以,如果你只是運行你的應用程序,onFinish的工作速度更快。

第二點是圍繞手動檢測超時的onTick方法的塊一段時間用布爾

private boolean tapBlock = false; 

private void beginTimer() 
{ 
    new CountDownTimer(10100, 1000) 
    { 
    public void onTick(long millisUntilFinished) 
    { 
     if (!tapBlock) 
     { 
      time.setText("Time: "+millisUntilFinished/1000); 
      if (millisUntilFinished<100) 
      { 
      tapBlock = true; 
      } 
     } 
    } 

    public void onFinish() 
    { 
     time.setText("Timeout!!!"); 
     finalTap++; 
     tapBlock = false; 
    } 
    }.start(); 
} 

這是後水龍頭一點,但它可能更快,你必須添加「 tapBlock「更新方法