如何让应用程序在第二个 activity 中打开一段时间?

How can I make the app open in the second activity for a certain amount of time?

我有一个应用程序可以接受用户输入并在第二个 activity 中显示它,我正在通过 savedPreferences 保存用户输入。但是如果我退出应用程序,它会返回到主 activity。当用户重新打开应用程序一段时间(24 小时)时,我如何打开第二个 activity?然后在那个时间段之后回去开始activity?

参考代码会有帮助。谢谢

然后您将需要一个 CountDownTimer,覆盖 OnStop 以将计时器的当前状态保存在 SharedPreference 中,当您打开应用程序时检查 SharedPreference 您存储的变量如果它不为零表示计时器未完成,请打开 SecondActivity 并使用存储值继续倒数计时器。

private void startTimer() {
    mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;

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

@Override
protected void onStop() {
    super.onStop();

    SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    editor.putLong("millisLeft", mTimeLeftInMillis);
    editor.putBoolean("timerRunning", mTimerRunning);
    editor.putLong("endTime", mEndTime);

    editor.apply();

    if (mCountDownTimer != null) {
        mCountDownTimer.cancel();
    }
}

主要活动

protected void onStart() {
    super.onStart();

    SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);

    mTimeLeftInMillis = prefs.getLong("millisLeft", START_TIME_IN_MILLIS);
    mTimerRunning = prefs.getBoolean("timerRunning", false);

    if (mTimerRunning) {
        mEndTime = prefs.getLong("endTime", 0);
        mTimeLeftInMillis = mEndTime;

        if (mTimeLeftInMillis <= 0) {
            
          } else {
           startActivity(new Intent(FirstActivity.this,SecondActivity.class);
        }
    }
}

代码有点生疏,在 java 中,但您可以这样做