2016-02-22 25 views
0

我對多線程沒有太多經驗,所以很好地幫助我。我有一個後臺線程,我連接我的谷歌API客戶端來找到我的當前位置。當我撥打myGoogleApiClient.connect()它嘗試連接,並且在連接時收到回叫,但在連接方法調用後,我的流程返回。我希望我的程序在那裏等待並繼續執行我的下一個任務。下面是代碼如何在線程中等待,直到它接收到來自谷歌的連接回調API客戶端

public class CurrentLocation implements GoogleApiClient.OnConnectionFailedListener,GoogleApiClient.ConnectionCallbacks{ 
    private GoogleApiClient mGoogleApiClient; 
    private String placesTextFile; 
    Context context; 
    String TAG="NearbyPlaces"; 

    CurrentLocation(Context context) { 
     this.context = context; 
     mGoogleApiClient = new GoogleApiClient 
       .Builder(context) 
       .addApi(Places.GEO_DATA_API) 
       .addApi(Places.PLACE_DETECTION_API) 
       .addOnConnectionFailedListener(this) 
       .addConnectionCallbacks(this) 
       .build(); 
    } 

    private void connect() { 
     Log.d(TAG,"run called"); 
     if(mGoogleApiClient.isConnected()) 
      findLocations(); 
     else 
      mGoogleApiClient.connect(); //Here my flow goes back but i want my program to wait here till it gets onConnected callback 

    } 
    private void findLocations(){ 
    // some code here that need to be executed when my client connects 
    } 
    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     Log.d(TAG,"Google Client is Connected"); 
     findLocations(); 
    } 
} 

我打電話給我的連接方法從計時器任務這樣

private void StartTracker() { 
     Log.d(TAG,"TimerTask is in waiting state now"); 
     timerScheduler.schedule(new TimerTask() { 
      @Override 
      public void run() { 

       while (isServiceRunning){ 
        try { 
         currentLocation.connect(); 
//video recorder should only be started when i will find out my current location successfully 
         videoRecorder.startVideoRecorder(); 
         Thread.sleep(getRandomRecordingDuration()); 
         videoRecorder.stopVideoRecorder(); 
         Thread.sleep(delayTime); 

        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 

       } 

      } 
     }, delayTime); 
    } 
+1

如何_your_'連接()'方法被調用?你沒有給我們足夠的代碼。等待應該在'connect()'的調用者中發生,並且它應該等待由onConnected()方法發出信號的信號量。 –

+0

@JimGarrison,爲什麼不在'connect()'中等待? – shmosel

+0

@JimGarrison我編輯了我的文章..再次檢查一遍 –

回答

1

根據你的代碼,你只想做之後每次你打電話的「連接」的東西方法,併成功connect.So也許你最好在回調「onConnected」做的事情。

相關問題