How to correctly and consistently simulate a location in Android?

Here is what I tried:

    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String provider = locationManager.getBestProvider(criteria, true);
    locationManager.addTestProvider(provider, false, false, false, false, true, true, true, 0, Criteria.ACCURACY_FINE);
    locationManager.setTestProviderEnabled(provider, true);

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Location location = new Location(provider);
            location.setLatitude(...);
            location.setLongitude(...);
            location.setAccuracy(Criteria.ACCURACY_FINE);
            location.setTime(System.currentTimeMillis());
            location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
            locationManager.setTestProviderLocation(provider, location);

            handler.postDelayed(this, INTERVAL);
        }
    };

    handler.postDelayed(runnable, INTERVAL);

The problem is, no matter how much I set INTERVAL, the marker on the Google map cannot stay in a mocking place. He always returns to its original position as long as the run()on Runnablewill not be called. I believe there is a legitimate way of mocking the location than my loop handler.

+4
source share
1 answer

When you call this line

locationManager.setTestProviderLocation(provider, location);

It sets the current location of this provider, let's say that my test provider is AbcProvider

String provider = "AbcProvider";
location.setProvider(provider);
locationManager.setTestProviderLocation(provider, location);
  • locationManager.getLastKnownLocation( "AbcProvider" );
  • onLocationChanged() , requestLocationUpdates ( "AbcProvider",...);

! , . , Google Maps, , LocationManager.

0

Source: https://habr.com/ru/post/1648027/


All Articles