我希望在点击按钮时获取当前的GPS位置。我编写了这段代码(如下所示),但这为NullPointerException
的位置对象提供了Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
。请告诉我的代码有什么问题?
代码:
@Override
public void onClick(View v) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
String cur_loc = "latitude = " + location.getLatitude() + "\n" + location.getLongitude(); //this is line 54 in my code
Toast.makeText(ctx, cur_loc, Toast.LENGTH_LONG).show();
}
AndroidManifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
答案 0 :(得分:0)
getLastKnownLocation (String provider)
可能会返回null。见Documentation:
返回指示上一个已知位置的数据的位置 从给定的提供者处获得的修复。
这可以在不启动提供程序的情况下完成。请注意这一点 位置可能已过时,例如,如果设备已转动 关闭并搬到另一个地方。
如果当前禁用了提供程序,则返回null。
尝试这种方法:
private Location getLastKnownLocation() {
mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
现在将其用作:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location myLocation = getLastKnownLocation();