gpt4 book ai didi

java - Android 倒计时器,新 Activity 继续计时器

转载 作者:行者123 更新时间:2023-12-01 13:47:37 26 4
gpt4 key购买 nike

我创建了一个可以运行的倒计时器,但它会在每次 Activity 时重新开始。我正在尝试保存倒计时值并在第二个 Activity 中使用它。以下是我的主要 Activity 页面上的倒计时代码。

    //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

我尝试存储倒计时值,然后在我的 Intent 中使用 passextra 来传递“定时”,但这不起作用。我四处搜寻,找不到任何有效的解决方案。任何帮助将不胜感激。

谢谢

================

编辑

================

公共(public)类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(){

}

==============

编辑2

            //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();


}

然后在我的第二个 Activity 中我得到了:

    MainActivity Counter1 = (MainActivity) getApplicationContext();
Counter1.starttimer();

TextView mCounter1TextField=(TextView)findViewById(R.id.textView4);
mCounter1TextField.setText("Seconds left: " + (Counter1));

最佳答案

扩展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(){
...
}
}

通过从 Activity 中调用 getApplicationContext() 来启动此计时器

MyApplication application = (MyApplication) getApplicationContext();
application.startTimer();

此外,请确保在 Android list 中重命名您的应用程序。

<application ... android:name=".MyApplication" .../>

关于java - Android 倒计时器,新 Activity 继续计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20243275/

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