[英]Is Thread.sleep() not letting other threads run?
我正在制作一个Android应用程序,并且制作了一个类来更轻松地分离和管理与获取用户位置有关的代码。 由于FusedLocationProviderClient需要一些时间来给出响应并执行onSuccess或onFailure侦听器中的代码,因此我制作了一个方法( waitForLocation()
),该方法基本上等待直到执行了一个侦听器或超过了时间限制。
waitForLocation()
方法是一种阻塞方法,它等待直到gotResponse
变为true
才能继续其余线程(如果超过了时间限制, gotResponse
也会变为true
)。
问题是,为了使代码停止流动直到gotResponse
为true
,我正在使用Thread.sleep()
方法,但是所有后台任务(例如CountDownTimer
和侦听器)似乎也与主程序冻结在一起。线程( CountDownTimer
未计时且侦听器从不执行)。
请帮忙! 提前致谢
这是我的课:
package com.sserrano.stormy;
import android.app.Activity;
import android.location.Location;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
public class UserLocationManager {
public static final String TAG = UserLocationManager.class.getSimpleName();
private FusedLocationProviderClient locationClient;
private Activity instActivity;
private double[] coords = {37.8267, -122.4233}, defaultCoords = {37.8267, -122.4233};
private volatile boolean gotResponse = false;
UserLocationManager(Activity instActivity){
this.instActivity = instActivity;
locationClient = LocationServices.getFusedLocationProviderClient(instActivity);
}
public double[] getLastCoords() {
try {
locationClient.getLastLocation().
addOnSuccessListener(instActivity, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null) {
coords = new double[]
{location.getLatitude(), location.getLongitude()};
}
gotResponse = true;
}
}).addOnFailureListener(instActivity, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
gotResponse = true;
}
});
} catch (SecurityException e){
return defaultCoords;
}
waitForLocation();
return coords;
}
public double[] getDefaultCoords(){
return defaultCoords;
}
private void waitForLocation(){
new CountDownTimer(5000, 5000){
@Override
public void onFinish() {
gotResponse = true;
Log.w(TAG, "Timed out waiting the result of the location request.");
}
@Override
public void onTick(long millisUntilFinished) {
}
};
try{
while(!gotResponse) {
Thread.sleep(Constants.getSleepIntervalDuration());
}
} catch (InterruptedException e) {
Log.w(TAG, "Interrupted while waiting the result of the location request." +
" The app will likely act like if the location was not received, " +
"even if it was.");
}
gotResponse = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.