gpt4 book ai didi

java - 如何在线程中等待,直到收到来自 google Api 客户端的连接回调

转载 作者:行者123 更新时间:2023-12-01 10:21:52 25 4
gpt4 key购买 nike

我对多线程没有太多经验,所以请帮助我。我有一个后台线程,在其中连接我的 google api 客户端来查找我当前的位置。当我调用 myGoogleApiClient.connect() 时,它会尝试连接,连接后我会收到回调,但在调用 connect 方法后,我的流程会返回。我希望我的程序在那里等待并继续执行下一个任务。这是代码

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

最佳答案

根据您的代码,您只想在每次调用“connect”方法并成功连接后执行一些操作。因此,也许您最好在回调“onConnected”中执行这些操作。

关于java - 如何在线程中等待,直到收到来自 google Api 客户端的连接回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35547146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com