【问题标题】:Get the last location in Android获取 Android 中的最后一个位置
【发布时间】:2016-03-18 12:51:12
【问题描述】:

我按照本教程 http://developer.android.com/training/location/retrieve-current.html 检索我的设备的位置,但它不起作用。

当我这样做时:

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

“mLastLocation”为空,为什么?

编辑

我试图在 Niru 的回答中这样做:

public Location setLocation()
    {
        Location location;
        final int MIN_TIME_BW_UPDATES = 300;
        final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 50;
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        String bestProvider = locationManager.getBestProvider(criteria, true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {}
        }

        location = locationManager.getLastKnownLocation(bestProvider);

        localStorage.putFloat("latitude", (float) location.getLatitude());
        localStorage.putFloat("longitude", (float) location.getLongitude());
        localStorage.commit();

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);



        return location;
    }

    @Override
    public void onLocationChanged(Location location)
    {
        localStorage.putFloat("latitude", (float) location.getLatitude());
        localStorage.putFloat("longitude", (float) location.getLongitude());
        localStorage.commit();
    }

但是“位置”是空的,为什么?

【问题讨论】:

  • Android 6.0 上的 Nexus 6p 和 Android 6.0.1 上的 Nexus 5 也有同样的问题,但它在 5.1.1 上的 Nexus 4 上运行良好,所以可能是平台问题...哪个版本你用的是安卓吗?

标签: java android google-api location


【解决方案1】:

你可以试试下面的代码sn-p:

public class LocationProvider
{
    private static final String     TAG         = "DEBUG";
    private static final String[]   provider    = new String[]
                                                {
            LocationManager.GPS_PROVIDER,
            LocationManager.NETWORK_PROVIDER,
            LocationManager.PASSIVE_PROVIDER
                                                };

    public Location getLocationByProvider(Context context)
    {
        Location location = null;
        // LocationManager locationManager = (LocationManager) context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        try
        {
            for (int i = 0; i < provider.length; i++)
            {
                if (locationManager.isProviderEnabled(provider[i]))
                {
                    // locationManager.requestLocationUpdates(provider[i], 0, 0, locationListenerGps);
                    location = locationManager.getLastKnownLocation(provider[i]);
                    if (location != null)
                    {
                        break;
                    }
                }
            }
        }
        catch (IllegalArgumentException e)
        {
            Log.d(TAG, "Cannot acces Provider " + provider);
        }
        return location;
    }

}

您还可以获取最佳提供商,然后从最佳提供商处获取位置。

mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            bestProvider = mLocationManager.getBestProvider(criteria, true);

希望这会对您有所帮助。 :-)

【讨论】:

  • 冷静,有美好的一天:-)
【解决方案2】:

getLastKnownLocation() 这将返回最后一个已知位置...在您重新安装应用程序后,它不会有任何最后一个已知位置...所以它会导致 NPE...而不是使用下面的代码

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

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

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;

【讨论】:

    【解决方案3】:

    文档本身说 getLastLocation 在位置不可用的情况下可能会返回 null。 为空时,在 OnConnected() 方法中调用 requestLocationUpdate 方法,如下所示:

    @Override
    public void onConnected(Bundle connectionHint) {
        mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mCurrentLocation == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
        }
    }
    

    在调用 requestLocationUpdates 之前,创建 mLLocationRequest 对象:

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);   
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    

    当位置可用时,OnLocationChanged 将自动触发。获取此回调的速率由您在创建请求对象时放入 setInterval() 的时间间隔定义。

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;        
    }
    

    然后您的位置对象将得到更新。

    点击此链接:http://developer.android.com/training/location/receive-location-updates.html

    【讨论】:

      【解决方案4】:

      感谢这篇文章,我解决了我的类似问题:Permission issues for location in android Marshmallow applicaton

      事实上,如果您使用compileSdkVersion 23(或更高版本),如果您希望您的应用程序在 Android 6.0+ 设备上正确运行,您必须处理新的 android 权限系统...更多信息可以在这里找到:@987654322 @。

      测试您的应用的一个快速而简单的解决方法是将您的 build.gradle 中的 compileSdkVersiontargetSdkVersion 更改为 22...

      但是,我认为没有明确的错误信息而只是一个空值,这很愚蠢......

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        • 2016-09-23
        • 2017-01-08
        相关资源
        最近更新 更多