连接到 Google Api 客户端时连接失败

Connecting fail when connect to the Google Api Client

我尝试连接到 Google API 客户端以在我的应用程序中实现一些功能。但由于某种原因,我无法连接到 Google API 客户端,因此我无法继续使用 Google 服务。

在我初始化 GoogleApiClient 之后,我检查 mGoogleApiClient.isConnected 是否总是得到 False,我不知道为什么。我将不胜感激任何帮助。谢谢。

请注意,一切都发生在后台服务上。

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();
}

您没有在正确的地方调用 .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();
}

在您的服务 onStartCommand 中连接 googleApiClient

@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;

}