我在Android中使用Google Play服务LocationClient。获取位置和位置更新时我没有任何问题。然而,当我的应用程序进入后台时,有时应用程序被android停止并且这个错误被抛出:
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:792)
at java.util.HashMap$KeyIterator.next(HashMap.java:819)
at com.google.android.gms.internal.l$a$a.onServiceDisconnected(Unknown Source)
at android.app.LoadedApk$ServiceDispatcher.doDeath(LoadedApk.java:1102)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1116)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4929)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
at dalvik.system.NativeStart.main(Native Method)
我试图多次摆脱这个错误,这就是我的locationClient代码现在正在运行的方式:
@Override
public void onConnected(Bundle arg0) {
counter = 0;
if (getLocationClient().isConnected()) {
getLocationClient().requestLocationUpdates(getLocationRequest(),
providerListener);
;
listen();
} else if (!getLocationClient().isConnecting()){
getLocationClient().connect();
}
}
@Override
public void onDisconnected() {
if(_locationClient!= null && !_locationClient.isConnected() && !_locationClient.isConnecting()) {
try {
connectLocationClient();
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法getLocationClient和getLocationRequest只是为了确保这些对象不为空:
private LocationClient getLocationClient() {
if (_locationClient == null) {
_locationClient = new LocationClient(context, this, this);
}
return _locationClient;
}
private LocationRequest getLocationRequest() {
if (_locRequest == null) {
_locRequest = new LocationRequest();
_locRequest.setInterval(fixTime);
_locRequest
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
return _locRequest;
}
对可能发生的事情有所了解?
谢谢!
编辑:
像shr指出的那样,在onDisconnected中调用connect()可能会导致这种情况,所以我确实从那里删除了它。同样在onConnected()中调用requestLocationUpdates()会导致一些麻烦,所以改为:
@Override
public void onConnected(Bundle arg0) {
requestUpdates();
}
public void requestUpdates(){
getLocationClient().requestLocationUpdates(getLocationRequest(),this);
}
@Override
public void onDisconnected() {
//Use a handler instead to reconnect
}
答案 0 :(得分:1)
我在google开发者控制台崩溃报告中在大规模部署的应用中发现了同样的问题。
我怀疑问题是由于我的应用尝试使用onDisconnected()
方法重新连接客户端,但在等待我的应用的下一个发布计划时无法验证该问题。
Another stackoverflow article通过建议(1)使用Handler
来避免在回调本身中调用connect()
方法,(2)避免重复使用{{}来向我提供关于该问题的优秀提示1}}对象,只是销毁旧的并创建一个新的。
我希望这会有所帮助。