gpt4 book ai didi

android - android中的全局定时器

转载 作者:行者123 更新时间:2023-12-05 00:14:27 26 4
gpt4 key购买 nike

我想制作一个计时器,它会在我的应用程序的每个 Activity 中显示。

我知道如何为下面的 Activity 设置计时器是我的代码

public class Timer extends Activity implements OnClickListener {
public TextView mTextField;
private Button btnstart;

public String formatTime(long millis) {
String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;

seconds = seconds % 60;
minutes = minutes % 60;

String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);

if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;

output = minutesD + " : " + secondsD;
return output;
}
public CountDownTimer Counter1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//Declare Start/Stop button
btnstart = (Button)findViewById(R.id.btnThread1);
btnstart.setOnClickListener(this);
//Button btnstop = (Button)findViewById(R.id.button02);
//Button btnpass = (Button)findViewById(R.id.button03);

//Declare Text fields to show time left
final TextView mCounter1TextField=(TextView)findViewById(R.id.txtThread1);
final TextView mCounter2TextField = (TextView)findViewById(R.id.txtThread2);
//final TextView mCounter3TextField=(TextView)findViewById(R.id.textView03);



//Counter 1
Counter1 = new CountDownTimer(120000 , 1000) {
public void onTick(long millisUntilFinished) {
mCounter1TextField.setText("Seconds left: " + formatTime(millisUntilFinished));
}

public void onFinish() {
mCounter1TextField.setText("Finished!");
// Counter1.start();
}
};
}

@Override
public void onClick(View v) {
if(v == btnstart)
{
Counter1.start();
}

}
}

我想知道如何让它全局化??

最佳答案

你可以有一个单例类来保存你的 CountDownTimer

// This is not a real singleton, Google to get a proper Java implementation
public class TimerSingleton {

// Should not be public, you should of course encapsulate access to that timer.
// static keyword says that one timer object is shared by all instance of TimerSingleton
public static CountDownTimer timer = new CountDownTimer();
}

// Access to the timer from an activity:
TimerSingleton.timer.start();

第二个选项是让您的计时器成为自定义应用程序类的成员:Use Application class for global variables

第三种选择:制作一个本地服务,在启动时启动计时器。

请记住,在选项 1 和 2 的情况下,如果操作系统决定终止您的应用程序,计时器将消失(即,当 Activity 重新创建时,CountDownTimer 对象将被重置)。

关于android - android中的全局定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13011939/

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