我在MainActivity中有两个活动设置的倒数计时器,我想当倒数计时器完成时它将进入下一个活动。但是它不会转到下一个活动的显示计时器。 这是我的代码:
公共类MainActivity扩展了AppCompatActivity {
TextView txtViewDays,txtViewHours,txtViewMinutes,txtViewSecond;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtViewDays = findViewById(R.id.days);
txtViewHours = findViewById(R.id.hours);
txtViewMinutes = findViewById(R.id.minutes);
txtViewSecond = findViewById(R.id.seconds);
start_countdown_timer();
}
private void start_countdown_timer()
{
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
formatter.setLenient(false);
final long[] startTime = new long[1];
String endTime = "23.06.2019, 22:56:10";
long milliseconds=0;
final CountDownTimer mCountDownTimer;
Date endDate;
try {
endDate = formatter.parse(endTime);
milliseconds = endDate.getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startTime[0] = System.currentTimeMillis();
mCountDownTimer = new CountDownTimer(milliseconds, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Long serverUptimeSeconds =
(millisUntilFinished - startTime[0]) / 1000;
String daysLeft = String.format("%d", serverUptimeSeconds / 86400);
txtViewDays.setText(daysLeft);
String hoursLeft = String.format("%d", (serverUptimeSeconds % 86400) / 3600);
txtViewHours.setText(hoursLeft);
String minutesLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) / 60);
txtViewMinutes.setText(minutesLeft);
Log.d("minutesLeft",minutesLeft);
String secondsLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) % 60);
txtViewSecond.setText(secondsLeft);
}
@Override
public void onFinish() {
Intent i = new Intent(MainActivity.this,New.class);
startActivity(i);
finish();
}
};
mCountDownTimer.start();
}
}
我该怎么办? N.B:代码已收集,我也尝试了,但我不能。谢谢
答案 0 :(得分:1)
对于您的代码,您需要1561330519961ms,这意味着必须经过几天才能调用onFinish方法。我尝试用1分钟的时间来代替您的代码
milliseconds = endDate.getTime();
,效果很好。计时器结束后,它更改了活动。
---编辑---
此示例代码将运行6秒钟,然后调用onFinish方法
milliseconds = 6000
mCountDownTimer = new CountDownTimer(milliseconds, 1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
Intent i = new Intent(MainActivity.this,Myclass.class);
startActivity(i);
finish();
}
};
mCountDownTimer.start();