您好,计划为该 Activity 开发 android 倒数计时器应用程序,当用户单击开始按钮时显示计时器倒计时并显示计时器倒计时,用户将转到剩余 Activity ,即使计时器在后台运行,如果用户单击停止则仅停止计时器.
我如何在服务中运行计时器并将时间更新到 activity android 中的 textview。
最佳答案
是的,你可以。我会给你一个我很久以前用过的代码示例。请记住,这不是使用按钮,但它会让您大致了解如何操作。此代码使用当前倒计时值更新 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 的 Activity 中需要的必要代码:
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"));
}
};
希望这对您有所帮助。
关于服务中的 Android 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23755981/