如何保存计时器的值?

laawzig2  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(318)

我有两个类:mainactivity.java和startgame.java。startgame.java中有倒计时。当我关闭应用程序并重新启动时,计时器不工作。我该怎么修?

public class StartGame extends AppCompatActivity {
long duration = TimeUnit.HOURS.toMillis(24);
long endOfTask = System.currentTimeMillis() + duration;
final String TAG = "STATE";
static SharedPreferences save;
public static final String APP_PREFERENCES = "save";
public static final String APP_PREFERENCES_TODO = "todo";
public static final String APP_PREFERENCES_CHRONOMETER = "chronometer";
Context context;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start_game);
    context = this;

    //Array
    String[] tasks = {"..."};
    // Calculate how many words are in the array
    int tasksLength = tasks.length;
    //Generate random
    int rand = (int) (Math.random() * tasksLength);

    //Set task
    String task = tasks[rand] + " ";
    TextView todo = (TextView) findViewById(R.id.todo);
    todo.setText(task);
    saveText();

    //Button Back START
    Window w = getWindow();
    w.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    Button buttonBack = findViewById(R.id.buttonBack);

    buttonBack.setOnClickListener(v -> {
        try {
            Intent intent = new Intent(StartGame.this, MainActivity.class);
            startActivity(intent);
            finish();
        } catch (Exception e) {

        } saveText();
    });
    // Button Back END

}

//System button Back START
    @Override
    public void onBackPressed () {
        super.onBackPressed();

        try {
            saveText();
            Intent intent = new Intent(StartGame.this, MainActivity.class);
            startActivity(intent);
            finish();
        } catch (Exception e) {

        }
        saveText();
    }
    //System button Back END

  void saveText () {
      TextView todo = (TextView) findViewById(R.id.todo);
      SharedPreferences save = StartGame.this.getSharedPreferences("save", MODE_PRIVATE);
      SharedPreferences.Editor editor = save.edit();
      editor.putLong(APP_PREFERENCES_CHRONOMETER, endOfTask);
      editor.putString(APP_PREFERENCES_TODO, todo.getText().toString());
      editor.apply();
  }

    void loadText () {
        TextView todo = (TextView) findViewById(R.id.todo);
        TextView chronometer = (TextView) findViewById(R.id.chronometer);
        SharedPreferences save = StartGame.this.getSharedPreferences("save", MODE_PRIVATE);
        todo.setText(save.getString(APP_PREFERENCES_TODO, todo.getText().toString()));
        //long finalTime = (save.getLong(APP_PREFERENCES_CHRONOMETER, Long.valueOf(endOfTask)) - System.currentTimeMillis());
         long finalTime = save.getLong(APP_PREFERENCES_CHRONOMETER, endOfTask);
        long finalLong = finalTime - System.currentTimeMillis();
        CountDownTimer timer = new CountDownTimer( finalLong, 1000) {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onTick(long l) {
                String duration = String.format(Locale.ENGLISH, "%02d : %02d : %02d", TimeUnit.MILLISECONDS.toHours(l), TimeUnit.MILLISECONDS.toMinutes(l) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toHours(l)), (l / 1000) % 60);
                chronometer.setText(duration);

            }

            @Override
            public void onFinish() {
                try {
                    Intent intent = new Intent(StartGame.this, EndGame.class);
                    startActivity(intent);
                    finish();
                } catch (Exception e) {
                }
            }
        }; timer.start();
    }

@Override
protected void onPause() {
    super.onPause();
    saveText();
    Log.d(TAG, "onPause");
}

@Override
protected void onStop() {
    saveText();
    super.onStop();
    Log.d(TAG, "onDestroy");

}

@Override
protected void onResume() {
    super.onResume();
    loadText();
    Log.d(TAG, "onResume");
}

@Override
protected void onDestroy() {
    super.onDestroy();
    saveText();
    Log.d(TAG, "onDestroy");
}

@Override
protected void onStart() {
    super.onStart();
    loadText();
    Log.d(TAG, "onStart");
}

@Override
protected void onRestart() {
    super.onRestart();
    loadText();
    Log.d(TAG, "onRestart");
}

@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    TextView todo = (TextView) findViewById(R.id.todo);
    outState.putLong("chronometer", endOfTask);
    outState.putString("todo", todo.getText().toString());
    saveText();
         Log.d(TAG, "onSaveInstanceState");

}

@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    TextView todo = (TextView) findViewById(R.id.todo);
    SharedPreferences save = StartGame.this.getSharedPreferences("save", MODE_PRIVATE);
    loadText();
    todo.setText(savedInstanceState.getString("todo"));
    Log.d(TAG, "onRestoreInstanceState");
}

}

如果在oncreate()中使用loadtext(),我的应用程序将无法正常工作,因为loadtext()的值在第一次启动时将等于null。
你能建议我修改代码吗?谢谢。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题