如何每周更新日期?

How to update a date weekly?

我正在对每周的周六实施倒计时,我希望当计数器达到零(周六)时,它将在下周六再次激活。但是我不知道如何每周更新日期。

我使用的代码如下:

  private void CountDown() {
        SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
        formatter.setLenient(false);

        String endTime = "12.03.2018, 15:05:36";

        Date endDate;

        try {
            endDate = formatter.parse(endTime);
            milliseconds = endDate.getTime();

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        startTime = System.currentTimeMillis();

        diff = milliseconds - startTime;


        mCountDownTimer = new CountDownTimer(milliseconds, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

                startTime=startTime-1;
                Long serverUptimeSeconds =
                        (millisUntilFinished - startTime) / 1000;

                String daysLeft = String.format("%d", serverUptimeSeconds / 86400);
                txtdays.setText(daysLeft);

                String hoursLeft = String.format("%d", (serverUptimeSeconds % 86400) / 3600);
                txthour.setText(hoursLeft);

                String minutesLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) / 60);

                txtmins.setText(minutesLeft);

                String secondsLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) % 60);
                txtsec.setText(secondsLeft);


            }

            @Override
            public void onFinish() {

            }
        }.start();

    }

感谢您的帮助。

您需要警报管理器服务才能执行此操作,这样您就可以为您的数据设置每周计划。

AlarmManager的使用方法请参考AlarmManager

简要介绍它的作用

Alarms (based on the AlarmManager class) give you a way to perform time-based operations outside the lifetime of your application. For example, you could use an alarm to initiate a long-running operation, such as starting a service once a day to download a weather forecast.

定时闹钟请参考Scheduling Repeating Alarms

编辑:您正在使用倒计时,如果应用程序未打开,倒计时将停止,使用闹钟管理器,您将解决此问题,因为它在后台运行。

编码愉快。