【问题标题】:Android - Google Maps returns null for location [duplicate]Android - Google Maps 为位置返回 null [重复]
【发布时间】:2018-03-02 19:04:05
【问题描述】:

我需要以 0.1 秒的频率在日志中查看我的位置。

mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
final Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        for (int i = 1; i < 100; i++)
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    mMap.setMyLocationEnabled(true);
                    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    Criteria criteria = new Criteria();
                    final Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
                    Log.d("Coordinates: ",location.getLongitude() + "," + location.getLatitude());
                }
            }, 100 * i);

我用模拟器在日志中看到坐标,但是当我通过 USB 连接手机时,我遇到了与Log.d() 对应的崩溃,并出现以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference

【问题讨论】:

    标签: java android google-maps


    【解决方案1】:

    如果没有找到以前记录的位置,或者找到的上一个位置是很久以前的并且它的 gps 数据已过期,则最后一个已知位置可以为空。

    如果找到的最后一个位置为空,您可以使用融合位置提供程序 API 并查找位置。你会在 onLocationChanged 回调中得到它。

    【讨论】:

    • 您将能够在用于启动位置更新的方法中设置更新间隔...您正在做的事情不会做您想做的事情
    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多