如何停止计时器

时间:2017-02-25 11:46:14

标签: android timer

嗨,我有一个按钮和一个计时器

我想运行一个计时器但是当我点击一个按钮时,计时器应该停止并且应该调用方法test()

这是我的代码:

public class MainActivity extends AppCompatActivity {
Button button;
int a=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button)findViewById(R.id.btn);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            a=6;
        }
    });
    new CountDownTimer(30000, 4000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (a<5)
            {
                Toast.makeText(MainActivity.this, ""+a, Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        public void onFinish() {
           test();
        }
    }.start();
}
private void test ()
{
    Toast.makeText(this, "test is run", Toast.LENGTH_SHORT).show();
}
}

3 个答案:

答案 0 :(得分:2)

您必须先定义它:

console.log(process.memoryUsage());

答案 1 :(得分:1)

使用取消关键字

<style name="MyRatingBar" parent="@android:style/Widget.DeviceDefault.RatingBar.Indicator">
    <item name="android:minHeight">48dp</item>
    <item name="android:maxHeight">48dp</item>
</style>

答案 2 :(得分:1)

private CountDownTimer timer;

timer=new CountDownTimer(30000, 4000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (a<5)
            {
                Toast.makeText(MainActivity.this, ""+a, Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        public void onFinish() {
           test();
        }
    }.start();

在按钮侦听器的timer.cancel() metod上调用onClick()