Android线程问题

我有以下代码,希望每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);
        }
    }
}

错误是…

Error executing MyAsyncTask:(2573): Only the original thread that created a view hierarchy can touch its views.

最佳答案
使用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);
                }
            }
        });
    }
}

相关文章

文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win1...
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由main...
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件...
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项...
文章浏览阅读8.9w次,点赞4次,收藏43次。前言:在Android上...
文章浏览阅读1.1w次,点赞4次,收藏17次。Android Studio提供...