android - 为什么定位应用程序崩溃

标签 android null crash

我正在尝试使用 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/

相关文章:

android - 网络服务发现 Android

用于搜索的 MySQL 正则表达式

c# - WPF4/C# - System.StackOverflowException 崩溃应用程序

php - 聊天中的PHP session ,浏览器崩溃

java - 如何设置一个 View ,当用户单击手机的后退按钮时,它返回到同一个java类中的 View

java - 如何将用户详细信息存储为 session

java - 如何处理创建对象后只能分配非空值的字段(Java)

java - 使用 Java 反射返回所有 null

c - Malloc 调用崩溃,但在其他地方工作

android - 从 Android SDK Manager 更新工具时出错