我已经申请了。这是一个按钮,显示您按下它的时间。每次我“杀死”应用程序时,计时器都会再次(自然地)从 0 开始。我怎样才能让应用程序保存按下按钮的时间,所以当应用程序被杀死,然后你打开它时,计时器就在你停止的时候。我有一些关于这是如何完成的,我认为它与 SharedPreferences 有关。
我的代码:
public class MainActivity extends ActionBarActivity {
Button button1;
Chronometer chromo;
protected long time;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1=(Button)findViewById(R.id.button1);
chromo=(Chronometer)findViewById(R.id.chromo);
button1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
chromo.setBase(SystemClock.elapsedRealtime()+time);
chromo.start();
}
else if( event.getAction() == MotionEvent.ACTION_UP){
time =chromo.getBase()-SystemClock.elapsedRealtime();
chromo.stop();
}
return true;
}
});
}}
最佳答案
保存在 SharedPreferences 中:
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
// We use an editor to insert values in SharedPreferences
Editor editor = prefs.edit();
// Saving the values
editor.putLong("myTime", time);
// Committing the changes
editor.commit();
检索保存的值:
long savedValue = 0l;
SharedPreferences prefs= getSharedPreferences("prefs", Context.MODE_PRIVATE);
if (prefs.contains("hello")){
savedValue = sharedpreferences.getLong("myTime", 0l));
}
关于java - 在应用程序中保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27841221/