我尝试过很多东西:
location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
但该位置始终设为null
。
答案 0 :(得分:0)
尝试将以下权限添加到清单。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
答案 1 :(得分:0)
以下是一些有用的代码段:
private void _getLocation() {
// Get the location manager
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Double longitude, latitude;
Location location = locationManager.getLastKnownLocation(bestProvider);
try {
latitude = location.getLatitude();
longitude = location.getLongitude();
} catch (NullPointerException e) {
latitude = -1.0;
longitude = -1.0;
}
}
但是,这可能会请求FINE_LOCATION访问权限。因此,您需要添加以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
最快的方法是使用最后一个位置,我使用它并且它非常快:
private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location location = null;
for (int i=providers.size()-1; i>=0; i--) {
location = lm.getLastKnownLocation(providers.get(i));
if (location != null)
break;
}
double[] gps = new double[2];
if (location != null) {
gps[0] = location.getLatitude();
gps[1] = location.getLongitude();
}
return gps;
}
您也可以参考位置管理器的this开发人员指南。
仅供参考:不要忘记根据您使用的方法添加以下权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>