【问题标题】:Persist values across the lifetime of an app - Pause / resume countdown timer在应用程序的整个生命周期中保持值 - 暂停/恢复倒数计时器
【发布时间】:2016-07-12 16:55:31
【问题描述】:

我想创建一个倒计时,这样当应用程序完全关闭时,倒计时计时器会暂停并保存。当应用程序再次打开时,倒计时从停止的地方继续。 我的想法是在应用程序关闭时将值“millisUntilFinished”保存在“onStop”中,并在“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();
}

【问题讨论】:

标签: android sharedpreferences countdown countdowntimer data-persistence


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多