Android UI 更新线程 - 保存和恢复它

标签 android save state restore

我该如何正确地做到这一点?

我有一个秒表,我在 onSaveInstance 中保存它的状态并在 onRestoreInstance 中恢复它的状态...

现在我遇到了以下问题:如果我在 onSaveInstance 中停止线程并且屏幕被锁定或关闭,onRestoreInstance 不会被调用并且秒表不会继续...
如果我不停止它,即使屏幕关闭或 Activity 不再处于 Activity 状态,秒表也会在后台运行......

那么通常处理这种事情的方法是什么?

附言:
我什至有一个可行的解决方案,一个局部变量,用于在 onStop 事件中保存运行状态并在 onStart 事件中重新启动线程......但我仍然想知道如果有一个使用 android 系统本身的“默认”解决方案....

最佳答案

好的。我现在最好明白你在做什么。我还以为你是用线程来计数呢。现在听起来您正在使用它来更新 UI。

相反,您可能应该做的是使用自调用 HandlerHandler 是可以异步运行的漂亮的小类。由于它们的多样性,它们在 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/

相关文章:

javascript - 如何使用功能组件从 Redux 存储中检索数据并避免 useSelector 和 useDispatch

javascript - 在 React 应用程序中使用 <audio> 标签,在点击时播放所选文件

android - 将数据从 RecyclerView Adapter 传递到 Parent Fragment

android - 配置更改后如何在android中保存膨胀的布局?

r - 在 Shiny session 结束时保存用户输入?

c# - 将 inkCanvas 中的图像保存为 png 或 jpeg 文件

android - 工具栏内的TextView与Butterknife一起为null

android - AsyncTask 适用于 Android 2.3.3 但不适用于 ICS

c# - 共享内存,写入文件

flutter - StatefulWidget 中的 State 对象何时销毁?