Android线程问题

时间:2010-08-22 14:42:15

标签: android timer android-asynctask

我有以下代码,我希望能够每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):只有创建视图层次结构的原始线程才能触及其视图。

  

1 个答案:

答案 0 :(得分: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);
                }
            }
        });
    }
}