我正在编写一个 android 应用程序,我在 Google Map 上有标记,应该将其更改为 GCM 收到的位置。我有一个全局静态列表,我将标记与 id 和位置一起保存在其中。我可以在收到消息时更改 GCMBaseIntentService 列表中对象的位置,但是当我想执行以下代码时:
mMarker.setPosition(new LatLng(member.getLatitude(),member.getLongitude()));
我得到以下异常:
01-13 18:52:38.118: E/AndroidRuntime(7605): FATAL EXCEPTION: IntentService[GCMIntentService-1041237551356-1]
01-13 18:52:38.118: E/AndroidRuntime(7605): java.lang.IllegalStateException: Not on the main thread
01-13 18:52:38.118: E/AndroidRuntime(7605): at maps.am.r.b(Unknown Source)
01-13 18:52:38.118: E/AndroidRuntime(7605): at maps.ar.d.b(Unknown Source)
01-13 18:52:38.118: E/AndroidRuntime(7605): at maps.y.ae.addMarker(Unknown Source)
01-13 18:52:38.118: E/AndroidRuntime(7605): at com.google.android.gms.maps.internal.IGoogleMapDelegate$Stub.onTransact(IGoogleMapDelegate.java:167)
01-13 18:52:38.118: E/AndroidRuntime(7605): at android.os.Binder.transact(Binder.java:279)
01-13 18:52:38.118: E/AndroidRuntime(7605): at com.google.android.gms.maps.internal.IGoogleMapDelegate$a$a.addMarker(Unknown Source)
01-13 18:52:38.118: E/AndroidRuntime(7605): at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
01-13 18:52:38.118: E/AndroidRuntime(7605): at com.example.MapViewActivity.showMember(MapViewActivity.java:529)
01-13 18:52:38.118: E/AndroidRuntime(7605): at com.example.MapViewActivity.updateMember(MapViewActivity.java:417)
01-13 18:52:38.118: E/AndroidRuntime(7605): at com.example.MapViewActivity.updateMembers(MapViewActivity.java:410)
01-13 18:52:38.118: E/AndroidRuntime(7605): at com.example.pushnotifications.GCMIntentService.onMessage(GCMIntentService.java:75)
01-13 18:52:38.118: E/AndroidRuntime(7605): at com.google.android.gcm.GCMBaseIntentService.onHandleIntent(GCMBaseIntentService.java:223)
01-13 18:52:38.118: E/AndroidRuntime(7605): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
01-13 18:52:38.118: E/AndroidRuntime(7605): at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 18:52:38.118: E/AndroidRuntime(7605): at android.os.Looper.loop(Looper.java:130)
01-13 18:52:38.118: E/AndroidRuntime(7605): at android.os.HandlerThread.run(HandlerThread.java:60)
我尝试在地图上添加一个按钮来刷新所有标记(使用完全相同的代码)并且效果很好。所以不知何故,问题是 GCM 在不同的线程或类似的东西中执行,似乎我无法从不同的线程更改标记......
我尝试了一个丑陋的解决方案:每秒刷新所有标记。但是从 MapViewActivity 创建一个线程给出了相同的异常:
private Thread MarkerUpdater = new Thread(
new Runnable() {
public void run() {
while(true) {
updateMembers();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
也许有人知道一个好的解决方案会是什么样子?