1
我想按下一個按鈕,並讓該按鈕觸發一個定時器,每秒增加一個變量。當我關閉應用程序時,我希望增加的時間暫停,當應用程序打開時,我希望它從最後的位置恢復。我需要做什麼?如何暫停/恢復處理程序/可運行?
這裏是我的代碼:
public class MainActivity extends ActionBarActivity {
public void save(){
Editor editor = pref.edit();
editor.putInt("countertest", counter);
editor.commit();
}//end of save
public void read(){
counter = pref.getInt("countertest", counter);
}//end of read
Handler testHandler = new Handler();
int counter;
TextView testView;
Button testButton;
Runnable Runnable0;
SharedPreferences pref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testView = (TextView) findViewById(R.id.testView);
testButton = (Button) this.findViewById(R.id.testButton);
pref = PreferenceManager.getDefaultSharedPreferences(this);
read();
testView.setText(Integer.toString(counter));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
read();
final Runnable Runnable0 = new Runnable() {
@Override
public void run() {
counter += 1;
testView.setText(Integer.toString(counter));
testHandler.postDelayed(this, 1000);
save();
}// end of if
};
/* button click */
testButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Start runnable */
testButton.setEnabled(false);
counter -= 5;
save();
testView.setText(Integer.toString(counter));
testHandler.post(Runnable0);
}// end of onClick
});// end of blingButton onClickListener
super.onResume();
}//end of onResume
@Override
protected void onPause() {
save();
testHandler.removeCallbacks(Runnable0);
super.onPause();
}//end of onPause
}
我想在哪裏存儲「int lastRunnableCall = Calendar.getInstance()。getTimeInMillis();」?在onCreate? – Justin
我不明白你的解釋,我仍然無法完成它的工作。 – Justin
對不起,我遲到的回覆。 'lastRunnableCall'和'onPauseTime'是你活動的變量。每次調用run()'方法時,您都會設置'lastRunnableCall',並且在調用'onPause()'時設置'onPauseTime'。 – Dreagen