除非服务停止,否则不会调用GoogleApiClient OnConnected

时间:2017-04-14 07:10:22

标签: java android google-api-client

我正在拨打连接到googleapiclient的服务。每当第一次调用服务时,一切都顺利进行,客户端连接,调用Onconnected。但是,当我不停地回忆服务的那一刻,我得到googleapiclient连接,但Onconnected永远不会被调用。为什么这样?是否需要每次终止服务。这是代码:

public class ALW extends Service implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener {
    private GoogleApiClient mGoogleApiClient;



    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
        Log.d("ALWFA", "Stopped");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("ALWFA", "Called");
        if (!mGoogleApiClient.isConnected()) {
            Log.e("ALWFA", "Called for Connection");
            mGoogleApiClient.connect();
        } else {
            Log.e("ALWFA", "Already Connected");
        }
        //Do Work
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        buildGoogleApiClient();
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.d("Google Client", "Connected");
        //Do work

    }

    @Override
    public void onConnectionSuspended(int i) {
        System.out.println("Connection Sus");
        buildGoogleApiClient();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("Connection Error", "onConnectionFailed:" + connectionResult.getErrorCode() + "," + connectionResult.getErrorMessage());
        buildGoogleApiClient();
        System.out.println("Connection Failed");
    }

    synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }


}

我在Onconenctiofailed中没有收到任何错误。通常代码卡在onStartCommand:“ALWFA Called”。每当第二次调用服务时。

1 个答案:

答案 0 :(得分:0)

你应该在再次调用它之前检查

   if(mGoogleApiClient!=null && !mGoogleApiClient.isConnected())
      {
        //Do your work
      }

并实施这些方法

  @Override
protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    if (mGoogleApiClient != null)
        mGoogleApiClient.disconnect();

}