Android 定时器正在服务中

1 android timer stopwatch timertask countdowntimer

您好,计划为该活动开发带有开始和停止按钮的 Android 倒数计时器应用程序,当用户单击开始按钮时显示计时器倒计时,并且即使计时器在后台运行,如果用户单击停止,则仅停止计时器,用户也会转到剩余的活动。

我如何在服务中运行计时器并将时间更新到活动android中的textview。

Aks*_*iom 5

是的你可以。我会给你一个我很久以前使用过的代码示例。请记住,这不是使用按钮,但它会让您大致了解如何操作。此代码使用当前倒计时值更新 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();
}}
Run Code Online (Sandbox Code Playgroud)

这是您想要更新 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"));

    }
};
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。