LocationClient auto reconnect at `onDisconnect`

♀尐吖头ヾ 提交于 2019-11-30 20:53:05
lpic

an even simpler solution is to do nothing in the OnDisconnect.

public void onDisconnect(){
     //do nothing to client
}

when need to use the client simply check if is connected

if(mLocationClient.isconnected()){
     mLocationClient.connect();
}

the Google Play Services seems to reconnect nicely with out fuss.

i have used this on 4.0.4 and 4.2.2 successfully.

I found the solution! Just use Handler.

@Override
public void onDisconnected() {

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            mLocationClient.removeLocationUpdates(mLocationListener);
            mLocationClient.disconnect();
            mLocationClient = null;

            mLocationClient = new LocationClient(mContext, mConnectionCallback, mConnectionFailedCallback);
            mLocationClient.connect(); // NOW WORKING
        }
    }
}

In the official documentation (http://developer.android.com/reference/com/google/android/gms/location/LocationClient.html), it's written that:

public void disconnect ()

"Closes the connection to Google Play services. No calls can be made on this object after calling this method."

So you cannot call a connect() just after, you have to recreate the LocationClient object like you did the first time in order to connect again.

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