I want to put something like a timer on the button, that is, I have a button, after pressing it becomes inactive, say for 2 hours, after two hours it is clickable again, but so that the timer keeps counting time even if the application is closed or minimized. How to make the button inactive, I know, help to understand how to make a timer.
I wrote the code so that when I pressed the button, she would write down the date and deactivate the button, and after that she would get the new date and find the difference, and when it is 10 seconds, she activates the button again, but the code does not work, explain why?
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
private String TAG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
textView = findViewById(R.id.textView);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
button.setEnabled(false);
SharedPreferences.Editor editor = preferences.edit();
long startTime = System.currentTimeMillis();
editor.putLong("Time", startTime);
editor.apply();
Log.d(TAG, "Time " + startTime);
}
});
long startMillis = preferences.getLong("Time", 0);
long now = System.currentTimeMillis();
Log.d(TAG, "Now " + now);
long difference = now - startMillis;
if (difference == 10000) {
button.setEnabled(true);
}
Log.i(TAG, "Time111: " + difference);
}
@Override
protected void onStart() {
super.onStart();
}
}