【问题标题】:Setting a scheduled task inside an activity在活动中设置计划任务
【发布时间】:2011-08-02 15:22:42
【问题描述】:

我有一个活动(实际上是 MapActivity),它有一个带有 mapView 和一个 textView 的 linearLayout,用于显示当前速度等。例如,我希望 textView 每 0.5 秒更新一次。

我知道这可以通过服务来完成(至少我是这样学会的),但我想知道是否可以在 MapActivity 本身中使用 Timer。我试过这种方法:

onCreate{
...
    updateTimer = new Timer(); 
    updateTimer.scheduleAtFixedRate(doRefresh, 0, updateInterval);
   }

   private Timer updateTimer;
   private TimerTask doRefresh = new TimerTask()
   {
    public void run()
    {
       updateData();
    }
   };

    private void updateData()
    {
       //update the textView with the data
    }
   private int updateInterval = 500;

但是,它给了我以下错误:

04-10 22:24:56.529: ERROR/AndroidRuntime(9434): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

那么,是否可以在不使用服务类的情况下以简单的方式完成我正在尝试的事情?

谢谢和问候, =)

【问题讨论】:

    标签: android android-activity scheduled-tasks


    【解决方案1】:

    在某些小部件上调用postDelayed(),提供Runnable500 作为延迟。 Runnable 应该做你想做的任何工作,然后再次调用postDelayed(),将其自身作为Runnable500 作为延迟。

    这避免了后台线程和服务,活动中的简单定时事件不需要这些线程和服务。

    【讨论】:

      猜你喜欢
      • 2011-01-19
      • 2011-10-04
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2011-07-22
      • 1970-01-01
      相关资源
      最近更新 更多