2016-02-22 23 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”做的事情。

相关问题