我正在订阅获取推送坐标的数据流,每次听众获得新点时,我都想在地图上放置一个标记。如何将drawMarker代码放在正确的线程或正确的范围内?
@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);
}
}
});
}
答案 0 :(得分:1)
您可以使用runOnUiThread
在GUI线程中运行代码:
runOnUiThread(new Runnable() {
@Override
public void run() {
// Your code to run in GUI thread here
}
});
答案 1 :(得分:0)
确保您的pubsub可以访问Context对象(可以是Application上下文或Service上下文)。然后将所需的代码放在run
方法中:
// 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);