2

我想在谷歌地图 v2 中更改地图的位置

但我已经在 TimerTask 中完成了...目标、缩放、方位等等,它说

“IllegalStateException - 不在主线程上

我应该怎么办?有什么帮助吗?

class Task extends TimerTask { 

    @Override 
    public void run() {
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(Zt)      // Sets the center of the map to Mountain View
                .zoom(12)                   // Sets the zoom
                .bearing(180)                // Sets the orientation of the camera to east
                .tilt(30)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder

        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }
}

Timer timer = new Timer();

timer.scheduleAtFixedRate(new Task(), 0, 20000);
4

1 回答 1

0

计时器任务在与 UI 线程不同的线程上运行。在 Android 中,不允许从非 UI 线程执行 UI 操作。使用runOnUiThread方法向 UI 线程发送操作:

class Task extends TimerTask { 

    @Override 
    public void run() {
        runOnUiThread(new Runnable() {
            @Override 
            public void run() {
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(Zt)      // Sets the center of the map to Mountain View
                        .zoom(12)                   // Sets the zoom
                        .bearing(180)                // Sets the orientation of the camera to east
                        .tilt(30)                   // Sets the tilt of the camera to 30 degrees
                        .build();                   // Creates a CameraPosition from the builder

                mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });
    }
}

Timer timer = new Timer();

timer.scheduleAtFixedRate(new Task(), 0, 20000);
于 2014-08-23T10:17:26.747 回答