有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android GPS跟踪问题

我试图为我的安卓应用程序获取位置,但getLastKnownLocation始终返回null,并且onLocationChanged从未被调用。我对我的应用程序使用以下权限:

ACCESS_NETWORK_STATE, 
ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION. 

GPS和互联网已打开,我的设备已打开。我还尝试了requestLocationUpdates的不同值

        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        locationManager.removeUpdates(this);

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) 
        {
            // no network provider is enabled
        } 
        else 
        {
            hasGPS      = true;
            location    = null;
            if (isGPSEnabled) 
            {
                if (location == null) 
                {
                    locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if (locationManager != null) 
                    {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) 
                        {
                            lat = location.getLatitude();
                            lng = location.getLongitude();
                        }
                    }
                }
            }

            if (isNetworkEnabled && location == null) 
            {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if (locationManager != null) 
                {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) 
                    {
                        lat = location.getLatitude();
                        lng = location.getLongitude();
                    }
                }
            }
        }

共 (2) 个答案

  1. # 2 楼答案

    如果GetLastKnownLocation从未通过该提供程序获得过位置,或者位置太旧,则GetLastKnownLocation将返回null。所以这并不意外。最有可能的情况是,你没有收到GPS信号,这可能需要几秒钟或几分钟(或者在许多建筑中完全失败)。再次检查GPS是否已在“设置”中打开,并查看通知区域中的闪烁圆圈——如果它从未变为实心,则您不会收到信号