在活动onStop上启动IntentService

时间:2019-01-24 16:43:24

标签: java android

我正在开发一个倒数计时器,即使应用程序处于后台或关闭状态,我也想使其仍在计时。

我尝试通过使用IntentService并在Activity的 onStop 中调用此方法来做到这一点:

private void startTimerService(TimerFragment timer){
    MyTimer myTimer = timer.getMyTimer();

    Intent intent = new Intent(this, IntentService.class);

    intent.putExtra("timer_running", myTimer.isRunning());
    intent.putExtra("pause", myTimer.isPause());

    intent.putExtra("init_time", myTimer.getInitTime());
    intent.putExtra("millis_left", myTimer.getTimeWhenStopped());
    intent.putExtra("end_time", myTimer.getEndTime());

    startService(intent);
}

这是我的Service类(仍在开发中...):

public class TimerIntentService extends IntentService {

private MyTimer myTimer;
private CountDownTimer countdownTimer;

public TimerIntentService() {
    super("TimerIntentService");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    return START_STICKY;
}

@Override
protected void onHandleIntent(Intent intent){
    Bundle extras = intent.getExtras();
    if(extras !=  null){
        myTimer = new MyTimer();

        myTimer.setIdExecution(extras.getLong("id_execution"));
        myTimer.setIdExercise(extras.getLong("id_exercise"));
        myTimer.setPosition(extras.getInt("position"));

        myTimer.setRunning(extras.getBoolean("timer_running"));
        myTimer.setPause(extras.getBoolean("pause"));

        myTimer.setInitTime(extras.getLong("init_time"));
        myTimer.setTimeWhenStopped(extras.getLong("millis_left"));
        myTimer.setEndTime(extras.getLong("end_time"));

        if(myTimer.isRunning()){
            createTimer(myTimer.getTimeWhenStopped());
            if(!myTimer.isPause()){
                myTimer.startTimer();
            }
        }
    }
}

private void createTimer(long t){
    CountDownTimer timer = new CountDownTimer(t, 1000) {
        @Override
        public void onTick(long l) {
            myTimer.setElapsedTime(l/1000);

            long hour = myTimer.getElapsedTime()/3600;
            long minute = myTimer.getElapsedTime()/60;
            long second = myTimer.getElapsedTime()%60;

            String s = String.format("%02d", hour) + ":"
                    + String.format("%02d", minute) +":"
                    + String.format("%02d", second);

            Log.v("Timer Service: ", s);

        }

        @Override
        public void onFinish() {
            cancel();
            myTimer.setRunning(false);

        }
    };

    myTimer.setTimer(timer);
}
}

目标是在关闭或最小化应用程序时,IntentService从其在活动中停止的位置开始倒计时,而在再次打开应用程序时,服务停止,并且应用程序计时器从服务停止倒计时的位置开始

问题:目前,当我在onStop上调用该服务时,该服务甚至还没有启动。 这是使用服务的正确方法吗? 在活动停止时启动它,然后在活动开始时停止它是正确的吗?还是应该让它一直运行?

0 个答案:

没有答案