我制作了一个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停止并且不强制关闭?
谢谢。
答案 0 :(得分: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();
...
}
});
}
}