在活动中设置计划任务

发布于 2024-10-31 08:26:04 字数 852 浏览 2 评论 0原文

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

我知道这可以通过服务来完成(至少这是我学会的方法),但我想知道是否可以使用 MapActivity 本身内部的计时器来做到这一点。我尝试了这种方法:

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()

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

谢谢你和问候, =)

I have an activity (MapActivity actually) that has a linearLayout with a mapView and a textView, for displaying current speed, among other things. The thing is that I would like the textView to be updated every 0.5 seconds, for example.

I know this can be done with a service (at least that is how I learnt to do it), but I was wondering if it is possible to do so using a Timer inside the MapActivity itself. I tried this approach:

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;

However, it gives me the following error:

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

Then, is it possible to do what I'm trying in an easy way, without using a service class?

Thank you and regards,
=)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

作妖 2024-11-07 08:26:04

在某些小部件上调用 postDelayed(),提供 Runnable500 作为延迟。 Runnable 应该执行您想要完成的任何工作,然后再次调用 postDelayed(),并将其自身作为 Runnable500 > 作为延迟。

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

Call postDelayed() on some widget, supplying a Runnable and 500 as the delay. The Runnable should do whatever work you want done, then call postDelayed() again with itself as the Runnable and 500 as the delay.

This avoids background threads and services, which are not needed for simple timing events in an activity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文