我对多线程没有太多经验,所以请帮助我。我有一个后台线程,我在其中连接我的谷歌 api 客户端以查找我的当前位置。当我调用myGoogleApiClient.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"中执行操作。
所以终于找到了我问题的答案。我使用这种技术来解决我的问题。
//for waiting to complete another job
synchronized (synchObj) {
try { synchObj.wait();}
catch (InterruptedException ie) {
}
}
//when job is done and want the execution from where it was stoped
synchronized (synchObj) {
synchObj.notify();
}
跟着这个人来解决我的问题 http://forums.devshed.com/java-help-9/block-thread-callback-method-called-thread-904920.html