如何在按下按钮时销毁Java中的CoundownTimer?

问题描述 投票:0回答:1

我制作了一个计时器,其计数时间为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停止并且不强制关闭?

谢谢。

java android countdowntimer
1个回答
2
投票

您不能使用onDestroy()关闭您的活动或片段。相反,您需要致电finish()

要关闭CountDownTimer,您需要将其设为一个类范围变量。在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();
          ...
       }
    });
   }

}
© www.soinside.com 2019 - 2024. All rights reserved.