我是Android编程新手。如果这是一个愚蠢的问题,请原谅我。
在我的应用中,我正在尝试开发一项功能,如果在手机中关闭位置服务,那么该应用会提示用户将其打开,方法是将其点击到位置设置页面按钮。问题是,在打开位置设置后,手机需要一些时间来提供位置坐标,因此假设显示坐标的片段在相同的时间内保持为空并且造成混淆。
我想知道的是,如果有任何方法可以安排执行获取位置坐标的函数,并确定有一些坐标可以获取。
我正在使用" getLastKnowLocation()"。获取位置的代码如下: -
public String getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
android.location.Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat,lon;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
try {
lat = location.getLatitude ();
lon = location.getLongitude ();
}
catch (NullPointerException e){
}
}
答案 0 :(得分:0)
创建一个布尔变量locationLoaded
。在以下代码行中:
try {
lat = location.getLatitude ();
lon = location.getLongitude ();
//set the value of variable to true once you get location
locationLoaded=true;
}
catch (NullPointerException e){
}
然后创建一个新的递归方法,它将继续检查位置,直到它没有加载,如下所示:
private void keepCheckingLocation(){
if(locationLoaded){
//location is loaded
return;
}
else{
//location is not loaded yet
try {
//wait for two seconds
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//call the method again to check the location
keepCheckingLocation();
}
}
一旦你调用了这个方法,它就不会让下一行代码执行,直到locationLoaded
不为真,而locationLoaded
只有在加载位置时才会为真。因此,只要您想等待加载位置,就可以使用此方法。
注意:如果您必须再次检查位置,请设置locationLoaded=false;
。它将使代码更有效。