最近,我创建了一个简单的应用程序来获取 gps 位置并在 android 手机上显示。一开始我可以在几次尝试后获得位置,但是在我重新安装 apk 文件后,getLastKnownLocation() 总是返回一个空值。
使用的开发环境: - API 10 姜饼 2.3.6 - 使用 GPS 提供程序
下面是我在我的android项目中应用的代码:
public class MyActivity extends MapActivity{
protected void onCreate(Bundle savedInstanceState) {
mapView = (MapView)findViewById(R.id.myTripMap);
mapController = mapView.getController();
mapView.setSatellite(false);
mapView.setStreetView(true);
mapView.displayZoomControls(false);
mapView.setBuiltInZoomControls(true);//
mapView.setClickable(true);
mapController.setZoom(14);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
updateMyCurrentLoc(location);
locationManager.requestLocationUpdates(provider, 2, 1,locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateMyCurrentLoc(location);
}
public void onProviderDisabled(String provider){
updateMyCurrentLoc(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
private void updateMyCurrentLoc(Location location) {
if (location != null) {
// other codes to get the address and display
Toast.makeText(getBaseContext(), "provider used : "+provider).show(); //testing purpose
}
else {
str = "No location found";
Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();
}
}
}
谁能提出一个可能的解决方案来解决 getLastKnownLocation() 返回的空值?任何帮助将不胜感激。谢谢。