代码之家  ›  专栏  ›  技术社区  ›  Lee Armstrong

Android线程问题

  •  3
  • Lee Armstrong  · 技术社区  · 16 年前

    我有以下代码,我想能够循环每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); 
            }
    
        };
    

    一旦我有了位置,就会被激发,覆盖任务执行得很好,当它被分配到一个菜单项时也会执行。

    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 回复  |  直到 16 年前
        1
  •  3
  •   Cristian    16 年前

    使用 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);
                    }
                }
            });
        }
    }
    
    推荐文章