我在启动后注册我的应用以接收位置更新。我的启动接收器正在启动一个执行初始化的服务:
@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的方式是否正确?例如我应该在服务中初始化它吗?
在后台进行此操作的建议方法是什么?
答案 0 :(得分:0)
希望它对你有所帮助。
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();
}
}
答案 1 :(得分:0)
使用以下解决方案:
googleApiInstance.blockingConnect(10, TimeUnit.SECONDS);
或者换句话说,不是在另一个线程中运行操作(这是connect
正在做的事情),而是在我自己的线程中运行它(我正在使用IntentService
)并管理我自己的连接生命周期。