3

我有以下代码,我希望能够每 30 秒循环一次。

MyLocation myLocation = new MyLocation();
    public LocationResult locationResult = new LocationResult() {
        @Override
        public void gotLocation(final Location location) {
            GeoPoint myGeoPoint = new GeoPoint(
                    (int) (location.getLatitude() * 1000000),
                    (int) (location.getLongitude() * 1000000));
            myMapController.animateTo(myGeoPoint);
            myMapController.setZoom(10);

            lat = location.getLatitude();
            lon = location.getLongitude();

            new OverlayTask().execute();


            Timer timer;
            timer = new Timer();
            timer.scheduleAtFixedRate(new MyTimerTask(), 30000, 30000); 
        }

    };

一旦我有了位置就会被触发,并且 OverlayTask 执行得很好,它也会在分配给菜单项以强制执行时执行。

但是在计时器内我得到一个错误。

public class MyTimerTask extends TimerTask {
    public void run() {
        try {
            Log.i(">>>>>>>>>>>> Refresh: ", "Success");
            new OverlayTask().execute();
        } catch (Exception e) {
            Log.e(">>>>>>>>>>>> Error executing MyAsyncTask: ", e.getMessage(), e);
        }
    }
}

错误是......

执行 MyAsyncTask 时出错:(2573):只有创建视图层次结构的原始线程才能接触其视图。

4

1 回答 1

3

使用runOnUiThread方法:

public class MyTimerTask extends TimerTask {
    public void run() {
        runOnUIThread(new Runnable(){
            public void run(){
                try {
                    Log.i(">>>>>>>>>>>> Refresh: ", "Success");
                    new OverlayTask().execute();
                } catch (Exception e) {
                    Log.e(">>>>>>>>>>>> Error executing MyAsyncTask: ", e.getMessage(), e);
                }
            }
        });
    }
}
于 2010-08-22T14:52:27.933 回答