Android 如何将UI元素中的信息返回到线程中

Android 如何将UI元素中的信息返回到线程中,android,multithreading,google-maps,Android,Multithreading,Google Maps,我用谷歌地图创建了一个应用程序。 我想做一些数学运算,并在一个一直运行的线程中更新谷歌地图的标记 我的线程需要知道当前googleMap的相机缩放以及LatLngBounds来更新标记 如果我这样做,它将完美工作: class updateMap implements Runnable{ private double currentZoom; private LatLngBounds screenRegion; @Override public void run(

我用谷歌地图创建了一个应用程序。 我想做一些数学运算,并在一个一直运行的线程中更新谷歌地图的标记

我的线程需要知道当前googleMap的相机缩放以及LatLngBounds来更新标记

如果我这样做,它将完美工作:

class updateMap implements Runnable{
    private double currentZoom;
    private LatLngBounds screenRegion;
    @Override
    public void run(){
        while(!threadStop){//threadStop is a boolean to stop threads when onDestroy() is called
                screenRegion = googleMap.getProjection().getVisibleRegion().latLngBounds;//fetches the screen's visible region
                currentZoom = googleMap.getCameraPosition().zoom;
            if(googleMap != null){//if my googleMap is fine
                if(currentZoom >= 13){ //if the Camera's zoom is greater or equal than 13
                    //do some maths...
                    //updates the markers on the GoogleMap
                }
            }
        }
    }
}
但是我知道不建议直接在线程中与UI线程交互,所以我将与UI线程交互的几行代码放在runOnUiThread()方法中,如下所示,但它不起作用。我的应用程序冻结,什么也没发生,ARN甚至没有出现

class updateMap implements Runnable{
    private double currentZoom;
    private LatLngBounds screenRegion;
    boolean map = false;
    @Override
    public void run(){
        while(!threadStop){//threadStop is a boolean to stop threads when onDestroy() is called
            runOnUiThread(new Runnable() {//Here I execute this piece of code on the UI thread to get the variables
                @Override
                public void run() {
                    if(googleMap != null){
                        map = true;
                        screenRegion = googleMap.getProjection().getVisibleRegion().latLngBounds;//fetches the screen's visible region
                        currentZoom = googleMap.getCameraPosition().zoom;
                    }
                }
            });
            if(map){//if my googleMap is fine
                if(currentZoom >= 13){ //if the Camera's zoom is greater or equal than 13
                    //do some maths...
                    runOnUiThread(new Runnable(){
                        @Override
                        public void run(){
                            //updates the markers on the GoogleMap
                        }
                    });
                }
            }
        }
    }
}
如果有人知道的话?也许我不尊重语法,或者我不应该使用runOnUiThread()方法两次或者其他什么


提前感谢。

我认为在您的情况下,使用UI线程获取数据是错误的。在单独的线程开始并作为参数传递之前执行此操作。

您正在进行的数学运算是否耗时?不,只有几个循环来检查我要添加到地图上的项目是否在地图的可视区域内。这将是一个解决方案,但我需要始终了解地图的当前缩放。每次循环重新开始时,我都必须检查缩放是否大于或等于13。