Android添加地图标记错误:java.lang.IllegalStateException:不在主线程上 [英] Android Add Map Marker Error: java.lang.IllegalStateException: Not on the main thread

查看:93
本文介绍了Android添加地图标记错误:java.lang.IllegalStateException:不在主线程上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在订阅获取推入坐标的数据流,我想在每次侦听器获得新点时在地图上放置一个标记.我需要怎么做才能将drawMarker代码放在正确的线程或正确的范围内?

I'm subscribing to a data stream that gets pushed coordinates, I want to place a marker on the map every time the listener gets a new point. What do I need to do to put the drawMarker code on the correct thread or in the correct scope?

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        enableMyLocation();
        subscribe();
    }

    public void drawLatestPoint(LatLng p) {
        System.out.println(p);
        mMap.addMarker(new MarkerOptions().position(p).title("Marker in Sydney"));
    }

    private void subscribe(){
        pubNub.subscribe()
                .channels(Arrays.asList("my_channel")) // subscribe to channel groups
                .execute();

        pubNub.addListener(new SubscribeCallback() {

            @Override
            public void message(PubNub pubnub, PNMessageResult message) {
                if (message.getMessage().get("lat") != null && message.getMessage().get("lng") != null) {
                    double lat = message.getMessage().get("lat").doubleValue();
                    double lng = message.getMessage().get("lng").doubleValue();
                    LatLng point = new LatLng(lat,lng);
                    drawLatestPoint(point);
                }
            }
        });
    }

推荐答案

您可以使用runOnUiThread在GUI线程中运行代码:

You can use runOnUiThread to run the code in the GUI thread:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
       // Your code to run in GUI thread here
    }
});

这篇关于Android添加地图标记错误:java.lang.IllegalStateException:不在主线程上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆