我正在尝试获取纬度和经度,下面是执行此操作的类...但是我在
位置 l = locMgr.getLastKnownLocation(bestProvider);
在 longt = Double.toString(loc.getLongitude());
即使在电话上,提供者也始终显示为 DummyLocationProvider
public class Util implements LocationListener {
public static LocationManager locMgr;
private static List<String> providers;
private static String bestProvider;
private Context context;
public static String lat;
public static String longt;
public Util(Context context) {
this.context = context;
if(locMgr == null) //Get LocationManager
locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void getLocations() {
//List All providers
providers = locMgr.getAllProviders();
//Get criteria
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get best provider
bestProvider = locMgr.getBestProvider(criteria, false);
printProvider(bestProvider);
//Get Last known location
Location l = locMgr.getLastKnownLocation(bestProvider);
if(l==null)
System.out.println("im null");
printLocation(l);
}
private void printLocation(Location loc) {
if(loc == null) { //means there is no recent location
getNewLocation();
}else
lat = Double.toString(loc.getLatitude());
longt = Double.toString(loc.getLongitude());
System.out.println("cached " + lat + " " + longt);
}
private void printProvider(String provider) {
System.out.println(provider);
LocationProvider info = locMgr.getProvider(provider);
System.out.println("provider= " + info.toString() + "\n\n");
}
private boolean getNewLocation() {
if(locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //This is executed since it can get locations faster than gps (is executed only if use wireless networks for locations is selected)
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
return true;
}else if(locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) { //This is exceuted if n/w locations is turned off & gps is turned on
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return true;
}else { //executed when gps & location by network is turned off..
return false;
}
}