我创建了一个可以正常工作的倒数计时器,但它会在每个活动上重新开始。我正在尝试保存倒计时值并在第二个活动中使用它。以下是我的主要活动页面上的倒计时代码。
//Countdown Start
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
final int j = (int) millisUntilFinished / 1000;
long timed;
timed = millisUntilFinished;
TextView textic = (TextView) findViewById(R.id.textView2);
textic.setText("" + (millisUntilFinished));
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textic = (TextView) findViewById(R.id.textView2);
textic.setText(Integer.toString((j)));;
}
});
}
public void onFinish() {
}
}.start();
//Countdown Finish
我已经尝试存储倒计时值,然后在我的意图中使用passextra传递“timed”,但这不起作用。我四处搜索,找不到任何有效的解决方案。任何帮助将不胜感激。
由于
=====
修改
=====
公共类MainActivity扩展了startscreen {
private CountDownTimer timer3;
public void onCreate(){
timer3 = new CountDownTimer(10000,100){
public void onTick(long millisUntilFinished) {
TextView displaytime = (TextView) findViewById(R.id.textView3);
displaytime.setText("" + (millisUntilFinished));}
public void onFinish() {
}
}.start();
};;
public void startTimer(){
}
public void cancelTimer(){
}
==============
//Counter 1
Counter1 = new CountDownTimer(10000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter1TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}
public void onFinish() {
mCounter1TextField.setText("Finished!");
// Counter1.start();
}
};
Counter1.start();
public void starttimer() {
Counter1.start();
}
然后在我的第二次活动中我得到了:
MainActivity Counter1 = (MainActivity) getApplicationContext();
Counter1.starttimer();
TextView mCounter1TextField=(TextView)findViewById(R.id.textView4);
mCounter1TextField.setText("Seconds left: " + (Counter1));
答案 0 :(得分:1)
扩展Application类并在那里添加全局计时器。你的课看起来像这样
public class MyApplication extends Application{
private CountDownTimer timer;
public void onCreate(){
super.onCreate();
timer = new CountDownTimer(10000,100){
.....
};
}
public void startTimer(){
...
}
public void cancelTimer(){
...
}
}
通过拨打getApplicationContext() from an activity
MyApplication application = (MyApplication) getApplicationContext();
application.startTimer();
另外,请确保在Android清单中重命名您的应用程序。
<application ... android:name=".MyApplication" .../>
答案 1 :(得分:0)
我建议在自己的类中编写CountDownTimer
并将其扩展为Service
,然后在想要启动计时器时启动服务,或者将其设置为Singleton以便所有活动访问相同的计时器。