【发布时间】:2014-05-20 09:31:10
【问题描述】:
您好计划为该活动开发和 android 倒计时计时器应用程序,当用户单击开始按钮时显示计时器倒计时和用户转到剩余活动,即使计时器正在运行后台,如果用户单击停止则仅停止计时器.
如何在服务中运行计时器并将时间更新到活动 android 中的 textview。
【问题讨论】:
标签: android timer countdowntimer timertask stopwatch
您好计划为该活动开发和 android 倒计时计时器应用程序,当用户单击开始按钮时显示计时器倒计时和用户转到剩余活动,即使计时器正在运行后台,如果用户单击停止则仅停止计时器.
如何在服务中运行计时器并将时间更新到活动 android 中的 textview。
【问题讨论】:
标签: android timer countdowntimer timertask stopwatch
是的,你可以。我给你一个我很久以前使用的代码示例。请记住,这不是使用按钮,但它会让您大致了解如何操作。此代码使用当前倒计时值更新 ActionBar MenuItem
这是服务:
public class CountDownTimerService extends Service {
static long TIME_LIMIT = 300000;
CountDownTimer Count;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Count = new CountDownTimer(TIME_LIMIT, 1000) {
public void onTick(long millisUntilFinished) {
long seconds = millisUntilFinished / 1000;
String time = String.format("%02d:%02d", (seconds % 3600) / 60, (seconds % 60));
Intent i = new Intent("COUNTDOWN_UPDATED");
i.putExtra("countdown",time);
sendBroadcast(i);
//coundownTimer.setTitle(millisUntilFinished / 1000);
}
public void onFinish() {
//coundownTimer.setTitle("Sedned!");
Intent i = new Intent("COUNTDOWN_UPDATED");
i.putExtra("countdown","Sent!");
sendBroadcast(i);
//Log.d("COUNTDOWN", "FINISH!");
stopSelf();
}
};
Count.start();
return START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
Count.cancel();
super.onDestroy();
}}
这是您想要更新 TextView 的活动中所需的必要代码:
startService(new Intent(context, CountDownTimerService.class));
registerReceiver(uiUpdated, new IntentFilter("COUNTDOWN_UPDATED"));
//Log.d("SERVICE", "STARTED!");
private BroadcastReceiver uiUpdated = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//This is the part where I get the timer value from the service and I update it every second, because I send the data from the service every second. The coundtdownTimer is a MenuItem
countdownTimer.setTitle(intent.getExtras().getString("countdown"));
}
};
希望这会有所帮助。
【讨论】: