Android: How to keep GPS active until more accurate location is provided?

心不动则不痛 提交于 2019-12-03 16:07:41

Try something like this. I think it is the right approach

private void createGpsListner()
{
    gpsListener = new LocationListener(){
        public void onLocationChanged(Location location)
        {
           curLocation = location;

           // check if locations has accuracy data
           if(curLocation.hasAccuracy())
           {
               // Accuracy is in rage of 20 meters, stop listening we have a fix
               if(curLocation.getAccuracy() < 20)
               {
                   stopGpsListner();
               }
           }
        }
        public void onProviderDisabled(String provider){}
        public void onProviderEnabled(String provider){}
        public void onStatusChanged(String provider, int status, Bundle extras){}
    };
}

private void startGpsListener()
{

    if(myLocationManager != null)
        // hit location update in intervals of 5sec and after 10meters offset
        myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, gpsListener);   
}

private void stopGpsListner()
{
    if(myLocationManager != null)
        myLocationManager.removeUpdates(gpsListener);
}

if you keep your LocationListener active, it should continue to receive updates to onLocationChanged() if the fix accuracy narrows. and indeed location.getAccuracy() will tell you the current accuracy

maybe set minTime and minDistance both to 0 to receive updates with greater frequency? will use more battery, but is more preise.

There is a example about get GPS location with timeout.

http://sikazi.blogspot.com/2010/09/android-gps-timeout.html#more

user2959031

To get GPS location periodically, get the location from onLocationChanged method of locationListener and in onResume method specify the timing in milliseconds for getting periodic updates

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