Zekirak Zekirak - 2 years ago 142
Android Question

Persist values across the lifetime of an app - Pause / resume countdown timer

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;

protected void onCreate(Bundle savedInstanceState) {

b1 = (Button) findViewById(R.id.b1);

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;

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() {

Answer Source

Use SharedPreferences.

   SharedPreferences prefs = 
         getSharedPreferences("PREF_NAME", MODE_PRIVATE); 
   int startTime = prefs.getInt("PAUSED_TIME", 0); //0 is the default value.


   SharedPreferences.Editor editor = 
            getSharedPreferences("PREF_NAME", MODE_PRIVATE).edit();
   editor.putInt("PAUSED_TIME", time);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download