2011-04-10 107 views
0

我有一个活动(实际上是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() 

话,岂不是可以做到我想要一个简单的方法,不使用服务类?

谢谢和问候, =)

回答

0

呼叫postDelayed()上的一些小部件,供应Runnable500的延迟。 Runnable应该做任何你想做的工作,然后再拨postDelayed()自己作为Runnable500作为延迟。

这可以避免后台线程和服务,这对于活动中的简单计时事件不需要。

+0

谢谢!救了我 – petoria 2011-04-10 22:04:26