gpt4 book ai didi

java - 如何在按下按钮时销毁Java中的CountdownTimer?

转载 作者:行者123 更新时间:2023-12-02 01:11:05 25 4
gpt4 key购买 nike

我做了一个计时时间为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 或 Fragment。相反,您需要调用 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();
...
}
});
}

}

关于java - 如何在按下按钮时销毁Java中的CountdownTimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59387375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com