在活动中设置计划任务
我有一个活动(实际上是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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在某些小部件上调用
postDelayed()
,提供Runnable
和500
作为延迟。Runnable
应该执行您想要完成的任何工作,然后再次调用postDelayed()
,并将其自身作为Runnable
和500
> 作为延迟。这避免了后台线程和服务,而活动中的简单计时事件不需要这些线程和服务。
Call
postDelayed()
on some widget, supplying aRunnable
and500
as the delay. TheRunnable
should do whatever work you want done, then callpostDelayed()
again with itself as theRunnable
and500
as the delay.This avoids background threads and services, which are not needed for simple timing events in an activity.