Android计时器在服务中

时间:2014-05-20 09:31:10

标签: android timer countdowntimer timertask stopwatch

嗨,当用户点击开始按钮显示计时器倒计时时,计划用该开始和停止按钮为该活动开发和安卓倒数计时器应用程序,如果用户点击停止,则用户转到剩余活动,即使计时器正在运行,也只停止计时器

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

1 个答案:

答案 0 :(得分:4)

是的,你可以。我给你一个我很久以前用过的代码示例。请记住,这不是使用按钮,但它会让您大致了解如何执行此操作。此代码使用当前倒计时值

更新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"));

    }
};

希望这有帮助。