我该如何正确地做到这一点?
我有一个秒表,我在 onSaveInstance
中保存它的状态并在 onRestoreInstance
中恢复它的状态...
现在我遇到了以下问题:如果我在 onSaveInstance
中停止线程并且屏幕被锁定或关闭,onRestoreInstance
不会被调用并且秒表不会继续...
如果我不停止它,即使屏幕关闭或 Activity 不再处于 Activity 状态,秒表也会在后台运行......
那么通常处理这种事情的方法是什么?
附言:
我什至有一个可行的解决方案,一个局部变量,用于在 onStop
事件中保存运行状态并在 onStart
事件中重新启动线程......但我仍然想知道如果有一个使用 android 系统本身的“默认”解决方案....
最佳答案
好的。我现在最好明白你在做什么。我还以为你是用线程来计数呢。现在听起来您正在使用它来更新 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。时钟可以继续在后台运行,但您不会再向用户显示它。
关于Android UI 更新线程 - 保存和恢复它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14377915/