Android:在 CountDownTimer 中的 onFinish() 之前延迟

标签 android countdowntimer

我试图创建一个简单的 Tap Counter 应用程序,但在它移动到 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));
}
}

最佳答案

首先,您是如何运行您的应用程序的?我注意到当我在 Debug模式下运行应用程序时,调试器消耗了我移动设备 50% 的性能。因此,如果您只是运行您的应用程序,onFinish 的运行速度会快得多。

第二点是在 onTick 方法中手动检测超时,并在一段时间后使用 bool 值阻止点击

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”添加到更新方法

关于Android:在 CountDownTimer 中的 onFinish() 之前延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815230/

相关文章:

android - Robolectric 与 test.R.java

android - CountDownTimer 不会让我调用 onDestroy

javascript - moment.js 显示错误时间

android - 在 Android Fragment 中实现 AsyncTask

Android Studio 无法覆盖默认主题

Android 应用程序有时加载时间过长

ios - 在 iOS 中开始计时器倒计时

java - 可以使用java从android SD卡读取文件

javascript - 如何在 JavaScript 中编写倒数计时器?

使用 CountDownTimer 的 android 无限 Toast 消息