我试图让这段代码排序几次。这是我迄今为止尝试过的场景……</p>
场景: 活动开始后,我想获取基于网络/gps 提供商的坐标(经纬度)。这应该在后台运行,并且应该一直检查直到 long & lat 不为空或“0.0”。因此,我使用 AsyncTask 尝试了以下代码,从而在 doInBackground 方法中使用了 LocationListener。
源代码:
public class GetLocation extends AsyncTask<String, String, String>
{
private myTest test;
boolean running =true;
private Context cont;
String addressString;
public GetLocation(myTest fr, Context contxt)
{
test = fr;
cont = contxt;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result)
{
test.GetContent();
}
@Override
protected String doInBackground(String... params) {
Looper.myLooper().prepare();
LocationManager locationManager;
locationManager = (LocationManager) cont
.getSystemService(Context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
locationManager.requestLocationUpdates(provider, 0, 0,
locationListener);
Looper.loop();
return addressString;
}
private void updateWithNewLocation(Location location) {
Constants.lat = Double.toString(location.getLatitude());
Constants.long = Double.toString(location.getLongitude());
}
}
问题: 但是,我也知道 Looper 可以帮助保持线程处于活动状态。我希望能够获得有效的坐标,这应该循环直到收到。我如何打电话一遍又一遍地获取位置,直到收到有效的位置?(我可以在我提供的循环中设置条件,但我不知道我应该如何以及应该调用什么方法来实现这一点)。如果可能,请提供代码片段。
干杯!