如何在按下按钮时销毁 Java 中的倒数计时器?

How To Destroy CoundownTimer in Java when the button is pressed?

我做了一个计时5秒的计时器,然后当我按下退出按钮时,计数器会自动停止?

这是我的计时器代码:

    public void startTimer(final long finish, long tick) {
        CountDownTimer t;
        t = new CountDownTimer(finish, tick) {

            public void onTick(long millisUntilFinished) {
                long remainedSecs = millisUntilFinished / 1000;
                textTimer.setText("" + (remainedSecs / 60) + ":" + (remainedSecs % 60));// manage it accordign to you
            }

            public void onFinish() {
                textTimer.setText("00:00");
                Toast.makeText(FloatingVideoWidgetShowService.this, "Waktu Habis", Toast.LENGTH_SHORT).show();
                long seek = videoView.getCurrentPosition();
                videoView.setKeepScreenOn(false);
                stopSelf();
                WritableMap args = new Arguments().createMap();
                args.putInt("index", index);
                args.putInt("seek", (int) seek);
                args.putString("url", playingVideo.getString("url"));
                args.putString("type", "close");

                sendEvent(reactContext, "onClose", args);
                onDestroy();
                cancel();
            }
        }.start();

    }

这是我按下停止/退出按钮时的代码:

        floatingWindow.findViewById(R.id.btn_deny).setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {
                long seek = videoView.getCurrentPosition();
                videoView.setKeepScreenOn(false);
                stopSelf();
                WritableMap args = new Arguments().createMap();
                args.putInt("index", index);
                args.putInt("seek", (int) seek);
                args.putString("url", playingVideo.getString("url"));
                args.putString("type", "close");

                sendEvent(reactContext, "onClose", args);
                onDestroy();
            }
        });

当点击 btn_deny 时,Cuntdowntimer 会停止并且不会强制关闭,这是怎么回事?

谢谢。

您不能使用 onDestroy() 关闭您的 activity 或片段。相反,您需要调用 finish().

要关闭 CountDownTimer,您需要将其设为 class 范围变量。在您的 startTimer 处准备计时器,然后通过调用 t.cancel() 来停止计时器,如下面的代码:

public class YourActivity extends Activity {
   // Declare the variable to be accessed later.
   CountDownTimer t;

   ...

   public void startTimer(final long finish, long tick) {
     t = new CountDownTimer(finish, tick) {
         ...
     }.start();

   }


   private void yourOtherMethod() {

    floatingWindow.findViewById(R.id.btn_deny).setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
          if(t != null) t.cancel();
          ...
       }
    });
   }

}