简体   繁体   中英

get gps location with android - not always working

I'm working on an android app, the idea is that the user logs and sends a form to a database. This form also contains the actual position of the user using gps.

This is the code I'm using:

Oncreate ->

 LocationManager locationManager = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);

        LocationListener locationListener = new MyLocationListener();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, locationListener);

Then the class ->

class MyLocationListener implements LocationListener {


        @Override
        public void onLocationChanged(Location loc) {

            long variance;
            variance = age_minutes(loc);


            if (variance < 1) {

                Log.v("asdf","we are inside" + variance);

                posH.longitude = String.valueOf(loc.getLongitude());
                Log.v("asdf", posH.longitude);
                posH.latitude = String.valueOf(loc.getLatitude());
                Log.v("asdf", posH.latitude);

                posH.valid = true;

            } else {

                Log.v("asdf","we are outside" + variance);
                posH.valid = false;
            }


        }

The problem with this is that it doesn't always work: For example, I open the form, I press send but onlocationchanged is not called until I wait 20 seconds, sometimes more, sometimes is never called, doesn't matter if I move or not.

I want a method that let me open the form, and automatically get the current gps position...

You can use start with last know location until you get more current data.

Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

From Android Location Strategies :

Obtaining user location from a mobile device can be complicated. There are several reasons why a location reading (regardless of the source) can contain errors and be inaccurate. Some sources of error in the user location include:

  • Multitude of location sources GPS, Cell-ID, and Wi-Fi can each provide a clue to users location. Determining which to use and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency.

  • User movement Because the user location changes, you must account for movement by re-estimating user location every so often.

  • Varying accuracy Location estimates coming from each location source are not consistent in their accuracy. A location obtained 10 seconds ago from one source might be more accurate than the newest location from another or same source. These problems can make it difficult to obtain a reliable user location reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM