Reputation: 29
I am programming an app which will send an SMS message when a set time runs out. When I change the orientation of the phone or temporary leave this activity, the timer still keeps counting, but the Stop button does not work, and the Start button is visible. I don't know how to save the settings; I know I have to use onSaveInstanceState
, but I don't know exactly what to put in there.
Code:
public void startThread(View view) {
stopThread = false;
sum = sec + mins;
if (sum == 0) {
Toast.makeText(Background.this, "Please enter a positive number", Toast.LENGTH_SHORT).show();
return;
}
ExampleRunnable runnable = new ExampleRunnable(sum);
new Thread(runnable).start();
btnStartThread.setEnabled(false);
}
public void stopThread(View view) {
stopThread = true;
btnStartThread.setEnabled(true);
}
class ExampleRunnable implements Runnable {
int seconds;
ExampleRunnable(int seconds) {
this.seconds = seconds;
}
@Override
public void run() {
for (; ; ) {
for (int i = 0; i < seconds; i++) {
if (stopThread) {
return;
}
if (i == sum-1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(check_sms.isChecked() && edit_phone_number.length() > 0) {
sendSMS();
}
}
});
}
Log.d(TAG, "startThread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Upvotes: 0
Views: 45
Reputation: 592
I would persist a flag like "hasTimerStarted" and set it true/false
depending if the timer has started or not and, if the timer has indeed started, I would save some other flags like "timerStartedEpoch" (the epoch number when time has started), "timerTimeoutMs" (the timeout ms).
This way, whenever you leave the activity and come back to it, you can load the flags and update the state based on them.
Upvotes: 2