我尝试连接到Google API客户端,以在我的应用程序中实现某些功能。但由于某些原因,我无法连接到Google API客户端,因为我无法继续使用Google服务。
在我初始化GoogleApiClient后,我会检查mGoogleApiClient.isConnected
是否一直都是假的,我不知道为什么。我将不胜感激任何帮助。谢谢。
请注意,所有事情都发生在后台服务上。
public class Background extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {
private String TAG = "Background";
private GoogleApiClient mGoogleApiClient;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"Start");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(ActivityRecognition.API)
.addApi(LocationServices.API)
.build();
if (!mGoogleApiClient.isConnected()) {
Log.e(TAG,"GoogleApiClient not yet connected");
} else {
Log.e(TAG,"GoogleApiClient connected");
}
return Service.START_STICKY;
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e(TAG, "Successfully added activity detection.");
} else {
Log.e(TAG, "Error: " + status.getStatusMessage());
}
}
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected");
mGoogleApiClient.connect();
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
答案 0 :(得分:0)
你没有在正确的地方调用.connect()。您正在构建客户端,之后必须调用.connect()。您将立即检查它是否已连接,它将永远不会连接。
请在.onStartCommand()中的.build()之后添加.connect()并删除此代码:
if (!mGoogleApiClient.isConnected()) {
Log.e(TAG,"GoogleApiClient not yet connected");
} else {
Log.e(TAG,"GoogleApiClient connected");
}
此外,删除它,因为它可能会让你处于不需要的状态:
@Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected");
// remove this -> mGoogleApiClient.connect();
}
答案 1 :(得分:0)
在您服务的onStartCommand
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"Start");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(ActivityRecognition.API)
.addApi(LocationServices.API)
.build();
if (!mGoogleApiClient.isConnected()) {
Log.e(TAG,"GoogleApiClient not yet connected");
mGoogleApiClient.connect(); // connect it here..
} else {
Log.e(TAG,"GoogleApiClient connected");
}
return Service.START_STICKY;
}