2011-04-10 98 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