I want to create a countdown such that when the app is completely closed, the countdown timer is paused and saved. When the app is opened again, the countdown resumes where it left off. My idea was to save the value "millisUntilFinished" in the "onStop" when the app is closed and in the "onResume" continue the countdown when the app is opened. The problem is that I don't know how to do it, someone help me?
The code of my countdown:
public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.b1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu
// this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void a(View view){
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
tv1.setText("La cuenta llega a 0 en: " + millisUntilFinished / 1000);
}
public void onFinish() {
tv1.setText("Listo!");
}
}.start();
}
Use SharedPreferences.
onResume(){
SharedPreferences prefs =
getSharedPreferences("PREF_NAME", MODE_PRIVATE);
int startTime = prefs.getInt("PAUSED_TIME", 0); //0 is the default value.
}
onPause(){
SharedPreferences.Editor editor =
getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
editor.putInt("PAUSED_TIME", time);
editor.commit();
}