2015-02-05 18 views
2

谷歌的API客戶端返回即使它被連接谷歌API客戶端連接在我的代碼將返回false

GoogleApiClient mGoogleApiClient; 
btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Log.i(TAG,"btn is clicked"); 
      buildGoogleApiClient(); 
      Log.i(TAG,"build google api completed"); 
      mGoogleApiClient.connect(); 
      if(mGoogleApiClient.isConnected()) 
      Log.i(TAG,"client conneted"); 
      Log.i(TAG,String.valueOf(mGoogleApiClient.isConnected())); 


     } 
}); 

protected synchronized void buildGoogleApiClient() { 
    Log.i(TAG, "Building GoogleApiClient"); 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
    createLocationRequest(); 
} 

protected void createLocationRequest() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
} 

提前感謝假值

+0

您可以添加ConnectionCallbacks和ConnectionFailedListener的代碼嗎?也許從他們打印出一些信息。 – TofferJ 2015-02-05 16:06:29

回答

0

使用這種方法來爲你返回true。

public RequestAssync connect(){ 
    SystemStatus ss = Android.request.connection(); 
    if(ss.isConnect()){ 
     return ss.getStatus(); 
    }else{ 
     return false; 
    } 
} 
6

mGoogleApiClient.connect();不是同步操作 - 這就是爲什麼你建立你的GoogleApiClient當設置了addConnectionCallbacks(this)

您必須等待onConnected()回調之前mGoogleApiClient.isConnected()將返回true並且您可以使用GoogleApiClient

+1

嗨快速的問題。當onConnected()被觸發時,我設置了一個回調來打印消息。之後,我設置了一個按鈕來打印「mGoogleApiClient.isConnected()」,但即使在onConnected()回調成功之後,它仍然打印爲false。你知道爲什麼嗎? – codeshark 2015-08-28 23:28:42

相關問題