我在开机后注册我的应用程序以接收位置更新。我的引导接收器正在启动一个执行初始化的服务:
@Override
protected void onHandleIntent(Intent intent) {
GoogleApiClient client = _googleApiBuilder.get()
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}有时,在onConnected回调方法中,我会收到异常指示,表明我还没有连接。在一些研究之后,我遇到了这个- GoogleApiClient is throwing "GoogleApiClient is not connected yet" AFTER onConnected function getting called
这让我思考,我初始化google api的方式是正确的吗?例如,我应该在服务中初始化它吗?
在后台执行此操作的建议方法是什么?
发布于 2015-11-01 03:49:09
希望能对你有所帮助。
public class LocationService extends Service implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener {
private static final String TAG = LocationService.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
@Override
public IBinder onBind(final Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initGoogleApi();
}
@Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onLocationChanged(final Location location) {
}
@Override
public void onConnectionFailed(final ConnectionResult result) {
}
@Override
public void onConnected(final Bundle bundale) {
createLocationRequest();
}
@Override
public void onConnectionSuspended(final int arg0) {
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
protected void createLocationRequest() {
final LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(Constants.INTERVAL);
mLocationRequest.setFastestInterval(Constants.FAST_INTERVAL);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(0);
startLocationUpdates(mLocationRequest);
}
private void initGoogleApi() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
}发布于 2015-11-20 20:42:45
而是使用了以下解决方案:
googleApiInstance.blockingConnect(10, TimeUnit.SECONDS);或者换句话说,我不是在不同的线程(这就是connect正在做的事情)中运行该操作,而是在我自己的线程(我正在使用IntentService)中运行它,并自己管理连接生命周期。
https://stackoverflow.com/questions/33455749
复制相似问题