有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计时器必须保持删除状态

 CountDownTimer (2000, 0000) {
    @Override
    public void onTick(long millisUntilFinished) {}

    @Override
    public void onFinish() {

        txt1.setText("...");
        txt1.setVisibility(View.VISIBLE);
        txt2.setText("...");
        txt2.setVisibility(View.VISIBLE);

        cancel(); //<----it deletes the Countdown Timer after finished

        }

}.start();

我把cancel()放在onFinish()。因此,当倒计时结束时,它会删除自己。 但当我关闭并重新启动应用程序时,活动会从头开始,计时器也会开始。 我怎样才能让它工作一次


共 (1) 个答案

  1. # 1 楼答案

    不,你不能这样做。重新启动application时,创建一个新的timer。如果您想实现它,请尝试将状态存储在SharedPrefense

    SharedPreferences sharedPreferences = getSharedPreferences("save",MODE_PRIVATE);
    
    if(!sharedPreferences.getBoolean("opened",false)){
        //what you want do once
      SharedPreferences.Editor editor = sharedPreferences.edit();
      editor.putBoolean("opened", true);
      editor.apply();
    }