我创建了一个倒数计时器,在 mm:ss 中具有良好的锁定输出
因此,如果我切换到之前的活动视图并使用计时器返回活动,一切看起来都很好但是;-):
- 计时器仍在后台运行 - 但它看起来刚刚开始,没有计数..
- 这样我可以启动第二个,第三个,......计时器,因为按钮已经处于活动状态
所以我知道我必须设置所有这些设置,这很正常。我必须设置
- startButton 禁用 - 当计数器运行时...
- 如果用户回来并且计数器仍然是 sctive,则刷新活动视图
也许你可以告诉我如何为 ANDROID 做到这一点?这是我的工作代码:
some imports....
public class BasicActivity extends Activity {
ImageButton start, stop;
TextView timer;
/** Called when the activity is first created. */
//Ist dei Verbindung zur XML
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_activity);
//TIMER
start = (ImageButton)findViewById(R.id.startButton);
stop = (ImageButton)findViewById(R.id.stopButton);
timer = (TextView)findViewById(R.id.basicCountDown);
timer.setText(getString(R.string.basic01)); // Platzhalter im Textfeld.
final MyCounter timer = new MyCounter(10000,1000);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
timer.start();
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();
}
});
}
public class MyCounter extends CountDownTimer{
public MyCounter(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
System.out.println("Timer Completed.");
timer.setText(getString(R.string.basic02));
//Spielt den TON ab, wenn die ZEit um ist. Siehe Methode playSound!
playSound();
//Notification
new AlertDialog.Builder(BasicActivity.this).setTitle(getString(R.string.app_name)).setMessage(getString(R.string.basicNotificationMessage)).setIcon(R.drawable.ic_launcher).setNeutralButton(getString(R.string.ButtonOK), null).show();
}
@Override
public void onTick(long millisUntilFinished) {
SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss");
// dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = new Date(millisUntilFinished);
timer.setText(dateFormat.format(date));
// System.out.println("Timer : " + (millisUntilFinished/1000));
System.out.println("Timer : " + dateFormat.format(date));
}
}
//Sound nach Ablauf der Zeit
public void playSound() {
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.ton_timer);
mp.start();
}
}