Android Add Map Marker Error: java.lang.IllegalStateException: Not on the main thread

╄→尐↘猪︶ㄣ 提交于 2020-01-25 12:10:12

问题


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);
                }
            }
        });
    }

回答1:


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
    }
});



回答2:


Make sure that your pubsub has access to a Context object (can be the Application context or the Service context). Then put the required code inside the run method :

// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
mainHandler.post(myRunnable);

Reference



来源:https://stackoverflow.com/questions/39301726/android-add-map-marker-error-java-lang-illegalstateexception-not-on-the-main-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!