【问题标题】:why location app crashing为什么定位应用程序崩溃
【发布时间】:2015-02-02 02:06:36
【问题描述】:

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


        }
}

【问题讨论】:

  • 堆栈跟踪到底是什么?
  • 我不知道。一个月前,我什至不了解 Java 的基础知识。你能告诉我,要通过哪个主题来实现我的目标吗?
  • @k3v1n4ud3 .....谢谢你先生。

标签: android null crash


【解决方案1】:

如果位置服务被禁用,此调用 locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); 将返回 null。您的应用程序崩溃了,因为您没有检查 location 变量是否为 null

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多