在应用的整个生命周期内保留值 - 暂停/恢复倒数计时器

时间:2016-07-12 16:55:31

标签: android sharedpreferences countdown countdowntimer data-persistence

我想创建倒计时,以便在应用完全关闭时,倒数计时器暂停并保存。当应用程序再次打开时,倒计时将从中断处继续。 我的想法是在关闭应用程序时在“onStop”中保存值“millisUntilFinished”,并在打开应用程序时“onResume”继续倒计时。 问题是我不知道怎么做,有人帮助我吗?

倒计时的代码:

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();
}

1 个答案:

答案 0 :(得分:1)

使用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();
}