我正在尝试使用 GoogleMap 显示我当前的位置。只要手机(galaxy s4)上打开“位置”,它就可以正常运行。但当我关闭手机上的“位置”时,它崩溃了。
Logcat 在以下行告诉提供者为空
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
我想弹出一条消息说“打开位置”,而不是让应用程序崩溃。有什么简单而好的方法可以做到这一点?
代码:
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private Marker marker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(32, 270)).title("Marker"));
mMap.setMyLocationEnabled(true);
LocationManager locationManager= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 14));
}
}
最佳答案
此调用locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
如果位置服务被禁用,
返回null
。您的应用崩溃了,因为您没有检查 location
变量是否为 null
。
关于android - 为什么定位应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270200/