0

我想創建一個倒計時,以便當應用程序完全關閉時,倒數計時器暫停並保存。當應用程序再次打開時,倒計時將從停止的地方恢復。 我的想法是在應用程序關閉時將「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(); 
} 
+1

使用[SharedPreferences](https://developer.android.com/training/basics/data-storage/shared-preferences.html) –

回答

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