Ok。私は今、あなたが何をしているのかをよく理解しています。スレッドを使ってカウントしていると思いました。現在、UI の更新に使用しているようです。
代わりに、おそらく行うべきことは、自己呼び出しを使用することHandler
です。 Handler
は、非同期で実行できる気の利いた小さなクラスです。それらは多様性があるため、Android のいたるところで使用されています。
static final int UPDATE_INTERVAL = 1000; // in milliseconds. Will update every 1 second
Handler clockHander = new Handler();
Runnable UpdateClock extends Runnable {
View clock;
public UpdateClock(View clock) {
// Do what you need to update the clock
clock.invalidate(); // tell the clock to redraw.
clockHandler.postDelayed(this, UPDATE_INTERVAL); // call the handler again
}
}
UpdateClock runnableInstance;
public void start() {
// start the countdown
clockHandler.post(this); // tell the handler to update
}
@Override
public void onCreate(Bundle icicle) {
// create your UI including the clock view
View myClockView = getClockView(); // custom method. Just need to get the view and pass it to the runnable.
runnableInstance = new UpdateClock(myClockView);
}
@Override
public void onPause() {
clockHandler.removeCallbacksAndMessages(null); // removes all messages from the handler. I.E. stops it
}
これが行うことは、実行される にメッセージを投稿することHandler
です。この場合、1 秒ごとに投稿されます。利用可能なときに実行されるメッセージ キューがあるため、わずかな遅延があります。Handlers
それらは作成されたスレッドでも実行されるため、UI スレッドで作成すると、複雑なトリックなしで UI を更新できます。のメッセージを削除してonPause()
、UI の更新を停止します。時計はバックグラウンドで実行し続けることができますが、ユーザーには表示されなくなります。