How do I disable a button with a timer and keep it disabled on restart?

Mark Denom :

So my goal is to click a button, disable it and start a timer, once the timer is up enable the button. Simple right? You would do something like this.

button1.onClick { 

button1.setEnabled(false);
    new CountDownTimer(60000, 1000) { //Set Timer for 5 seconds
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                   button1.setEnabled(true);
            }
        }.start()

}

However.. If the user closes the app while the timer is running the button will be enabled again, restarting the timer. so instead of having to wait for 60 seconds the user can just close the app and open it within 10 seconds.

So my question is, how do I disable the button for 60 seconds and keep it disabled even if the user closes and opens the app until 60 seconds has passed?

GhostCat salutes Monica C. :

You have to persist that information within a data store that keeps it even when the app is switched off.

One way to do that would be to use https://developer.android.com/training/data-storage/shared-preferences

You have to get a timestamp when starting the timer, or compute the "end time" for the timer. You then save that information, and whenever the app starts up, you first check if your preferences contain such a time stamp. And if so, you check whether you are still in that "timed" window.

Thr key things to remember: you have to remove the persisted information when the timer is up, and: if somebody changes the system clock in the mean time, you got a problem, too. Dealing with that is possible, but requires more effort.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110487&siteId=1