如何在Android中正确一致地模拟位置?

时间:2016-07-15 14:56:27

标签: java android gps

这是我尝试的内容:

    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);

问题是,无论我设置INTERVAL多低,谷歌地图上的标记似乎都不会停留在模拟位置。它始终闪回原始位置,直到run()再次调用Runnable为止。我相信有一种合法的方式来模拟位置而不是我的循环Handler。

1 个答案:

答案 0 :(得分:0)

当你拨打这一行时

locationManager.setTestProviderLocation(provider, location);

它设置了此提供程序的当前位置,假设我的测试提供程序是AbcProvider

String provider = "AbcProvider";
location.setProvider(provider);
locationManager.setTestProviderLocation(provider, location);
  • locationManager.getLastKnownLocation( “AbcProvider”);返回当前设置的位置
  • 如果您调用 requestLocationUpdates(“AbcProvider”,...),
  • onLocationChanged()将被触发;

您的代码没有问题!但要明确你想看到嘲弄的结果。运行代码后,如果您查找 Google地图应用本身,则模拟将无法正常工作,因为它无法通过LocationManager获取位置。