getLastKnownLocation() returns null [closed]

微笑、不失礼 提交于 2019-11-26 08:38:19

问题


I have read a lot of Q&As on this topic here on SO but I have to say that none of them works.

My problem is that, even though I have GPS enabled, I cannot get a location unless I open Google Maps and get my location and then go back to the app, which is definitely not an option for the users.

I have the following function to get the location.

public Location getCurrentLocation() {
    LocationManager locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location myLocation = locationManager.getLastKnownLocation(provider);

    return myLocation;
}

Is there anything I\'m missing on how to solve this? I have also tried this http://developer.android.com/training/location/retrieve-current.html#last-known but still returns null.

Thanks in advance


回答1:


Is there anything I'm missing on how to solve this?

GPS radios are powered down normally, as they are major battery drain. Hence, getLastKnownLocation() can frequently return null or a stale location, because nothing is checking for location fixes. getLastKnownLocation(), therefore, is only useful if you have a casual interest in the location and are happy if there is no location.

If you need to know the location, you will need to use requestLocationUpdates() or similar stuff, to cause Android to power on the GPS radio and actively try to find the location.



来源:https://stackoverflow.com/questions/30664878/getlastknownlocation-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!