本文介绍了在Android的全球计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使这将是对我的应用程序的每个活动显示计时器。
I want to make a timer which will be shown on every activity of my application.
我知道如何使下面的一个活动的定时器是我的code
I know how to make a timer on an activity below is my code
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();
}
}
}
我想知道如何使全球??
I want to know how to make it global??
推荐答案
我已经通过一个定时器在一个活动并调用其保护功能在我的其他活动解决我的问题。
I have solved my problem by making a timer in one activity and calling its protected function in my other activity.
这是startTimer函数启动定时器:
This is the startTimer function to start the timer:
private void startTimer(){
if (mTimer == null) {
mTimer = new Timer();
}
if (mTimerTask == null) {
mTimerTask = new TimerTask() {
@Override
public void run() {
Log.i(TAG, "count: "+String.valueOf(count));
sendMessage(UPDATE_TEXTVIEW);
do {
try {
Log.i(TAG, "sleep(1000)...");
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} while (isPause);
count ++;
}
};
}
if(mTimer != null && mTimerTask != null )
mTimer.schedule(mTimerTask, delay, period);
}
和这是公共函数,可用于通过任何其他活动
and this is the public function which can be used by any other activity:
public String valueOfTimer()
{
return String.valueOf(count);
}
这是我如何让其他活动的值:
and this is how I am getting the value on other activity:
private void updateTime()
{
TimerActivity tm = new TimerActivity();
String time = tm.valueOfTimer();
t2.setText(time);
System.out.println("Time::"+time);
}
这篇关于在Android的全球计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!