【问题标题】:Android UI Update Thread - saving and restoring itAndroid UI 更新线程 - 保存和恢复它
【发布时间】:2013-01-17 11:19:24
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 您希望秒表在用户不再看到活动时继续吗?即,如果用户接到电话,秒表应该停止还是继续?
  • 秒表应该停止,当活动不可见时......如果它继续运行只是浪费资源......
  • 如果你想在它用完时发出通知或通过通知显示它倒计时。
  • 我也想要那个,但因此我使用的是android AlarmManager ...所以如果活动不可见,可以停止秒表(只是一个视觉反馈)......和一个线程对于警报来说不够安全......它可能会被杀死......服务将是一种替代方案,但我读到,考虑到资源,AlarmManager 更好......

标签: android save state restore


【解决方案1】:

好的。我现在更好地理解你在做什么。我以为你在用线程来计数。现在听起来您正在使用它来更新 UI。

相反,您可能应该做的是使用自调用HandlerHandlers 是可以异步运行的漂亮小类。由于它们的多样性,它们在 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 发送消息,该Handler 将运行。在这种情况下,它每 1 秒发布一次。因为Handlers 是可用时运行的消息队列,所以会有轻微 延迟。它们也在创建它们的线程上运行,因此如果您在 UI 线程上创建它,您将能够更新 UI,而无需任何花哨的技巧。您删除 onPause() 中的消息以停止更新 UI。时钟可以继续在后台运行,但您不会再向用户显示它。

【讨论】:

    【解决方案2】:

    我刚开始接触 Android 编程,但我认为在这种情况下不会调用 onRestoreInstance,因为您不会从一个活动切换到另一个活动。我认为你最好的选择是调用onPause,然后如果你需要它会调用onSaveInstance,但使用onResume,它可能会或可能不会调用onRestoreInstance

    【讨论】:

    • onPauseonResume 可以替代我的方式(使用 onStoponStart),但我也没有在 onResume 事件中获得 Bundle。 . 无论如何都会调用onSaveInstance 事件,但之后永远不会调用onRestoreInstance...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多