如何使倒数计时器与当地时间同步?

时间:2019-02-20 18:41:51

标签: android

所以我有两个活动。 Activity1打开到Activity2,在Activity2上,我有一个30倒数计时器和一个文本时钟。活动打开时,倒数计时器将自动启动。

两个显示秒,我希望倒数与时间同步。就像我希望倒计时的秒数与时间同步,并使它们同时更改。目前他们的时钟已不同步,倒数计时器将在秒数改变后半秒改变。

我假设/ d我的解决方法是将活动从打开推迟到下一秒开始。我尝试过通过实现处理程序来寻找解决方案,但是我所看到的是,您只能将活动从X秒钟开始延迟。我还看到了有关使其在一天中的特定时间启动的解决方案,但是我希望我的应用程序在一天中的任何时间都可以使用,并且只要您打开该活动就可以重新启动计时器。

我对Activity2的代码如下(删除了不相关的位):

public class Main2Activity extends AppCompatActivity {
    private static final long START_TIME_IN_MILLIS = 1800000;
    private TextView mTextViewCountdown;
    private CountDownTimer mCountDownTimer;
    private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
    private boolean mTimerRunning;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);


        //clock
        final TextClock textClock = (TextClock) findViewById(R.id.textClock);
        textClock.setFormat12Hour("hh:mm:ss a");


        //calendar
        LocalDate currentDate = LocalDate.now();
        Calendar calendar = Calendar.getInstance();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy");
        String date = currentDate.format(formatter);
        LocalDate parsedDate = LocalDate.parse(date, formatter);

        TextView textViewDate = findViewById(R.id.TVD);
        textViewDate.setText(date);


        //countdownTimer
        mTextViewCountdown = findViewById(R.id.text_view_countdown);
        mCountDownTimer = new CountDownTimer(mTimeLeftInMillis,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeLeftInMillis = millisUntilFinished;
                mTimerRunning = true;
                updateCountDownText();

            }

            @Override
            public void onFinish() {

            }
        }.start();
    }
    //end of onCreate


    //countdownTimer part2
    private void updateCountDownText() {
        int days = 0;
        int hours = 0;
        int minutes = (int) mTimeLeftInMillis / 1000 / 60;
        int seconds = (int) mTimeLeftInMillis / 1000 % 60;

        String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d:%02d:%02d", days, hours, minutes, seconds);

        mTextViewCountdown.setText(timeLeftFormatted); 
    }
}
//end of Main

Activity1的代码只是一堆打开其他活动的按钮。

0 个答案:

没有答案