[英]Android: Stop AnimationDrawable after specified time, resume onResume(), pause onPause()
[英]Android : Restore time in resume
我有一個問題,我的應用中有一個計時器,當我返回主窗口並返回到計時器活動時,我只想從CountDownTimer恢復計時器的時間,該如何進行? Bundle對我和類似的主題沒有幫助:(我將非常感謝您的幫助。
public class Timer extends Activity {
private boolean start = false; // Semafor to button
private Chronometer timer; // Chronometr
private CountDownTimer count; // CountDown class
private final long startTime = 30 * 1000; // High
private final long end = 1 * 1000; //LOw
private ImageButton startB; // Button
private int VIBRATION_TIME = 1000; //vibration time
private Bundle state = new Bundle(); //button state
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
this.timer = ((Chronometer) findViewById(R.id.chronometer1));
count = new MyCountDownTimer(startTime, end);
timer.setText("00:" + String.valueOf(startTime / 1000));
startB = (ImageButton) this.findViewById(R.id.start_pause);
startB.setBackgroundResource(R.drawable.start_button);
startB.setOnClickListener(new View.OnClickListener() {
// click init
@Override
public void onClick(View v) {
start = !start;
if (start == true) {
count.start(); // start count
startB.setBackgroundResource(R.drawable.stop_button);
} else {
count.cancel(); // pause count
startB.setBackgroundResource(R.drawable.start_button);
}
}
});
}
....
@Override
protected void onResume() {
super.onResume();
start = state.getBoolean("Button");
}
@Override
protected void onPause() {
super.onPause();
state.putBoolean("Button", start);
//count.cancel(); I don't wanna this!
}
class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
timer.setText("00:00");
// TO DO :
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(VIBRATION_TIME);
startB.setBackgroundResource(R.drawable.start_button);
}
@Override
public void onTick(long millisUntilFinished) {
long tmp = millisUntilFinished / 1000;
timer.setText("00:" + tmp);
}
}
}
利用onSaveInstanceState
。 重寫此方法,並將您當前的時間保存到Bundle中。 然后,在onCreate
,從Bundle中提取值並將其應用於視圖。
嗯,是的,Alex說的沒錯,但我有新主意。 CountDownTimer開始計數,我們單擊了backButton活動被殺死,但是CountDownTimer仍在計數,但是當我再次使用此活動時,我可以運行新計時器,這很瘋狂,有任何辦法可以做到這一點:在create方法中,我們檢查CountDownTimer仍在運行,我們只是更新了一個計時器,但如果不是,我們是否會從new中創建所有內容? 現在,我的解決方案很棘手:重寫onBackPressed()並添加此moveTaskToBack(true); 但這不返回我的mainActivity,而是返回電話屏幕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.