在Android设备上模拟位置

时间:2016-09-12 13:08:03

标签: android gps android-location

我正在尝试测试使用GPS位置更新的应用。我试图通过模拟设备的位置来使其在室内工作时无法获得任何GPS信号。我按照教程here进行了操作,但是当我的应用运行时,它仍然没有获取任何位置更新。

有人能发现我的代码有什么问题吗?

        MockLocationProvider mock = new MockLocationProvider(LocationManager.GPS_PROVIDER, this);
        mock.pushLocation(-12.34, 23.45);

        LocationManager locMgr;

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

    }

    @Override
    public void onLocationChanged(Location Loc) {
        double lat = Loc.getLatitude();
        double lon = Loc.getLongitude();
        String l = "Longitude: " + lon + " Latitude: " + lat;
        Toast.makeText(getApplicationContext(), l ,Toast.LENGTH_SHORT).show();
    }


public class MockLocationProvider {
        String providerName;
        Context ctx;

        public MockLocationProvider(String name, Context ctx) {
            this.providerName = name;
            this.ctx = ctx;

            LocationManager lm = (LocationManager) ctx.getSystemService(
                    Context.LOCATION_SERVICE);
            lm.addTestProvider(providerName, false, false, false, false, false,
                    true, true, 0, 5);
            lm.setTestProviderEnabled(providerName, true);
        }

        public void pushLocation(double lat, double lon) {
            LocationManager lm = (LocationManager) ctx.getSystemService(
                    Context.LOCATION_SERVICE);

            Location mockLocation = new Location(providerName);
            mockLocation.setLatitude(lat);
            mockLocation.setLongitude(lon);
            mockLocation.setAltitude(0);
            mockLocation.setTime(System.currentTimeMillis());
            mockLocation.setElapsedRealtimeNanos(System.currentTimeMillis());
            mockLocation.setAccuracy(2);
            lm.setTestProviderLocation(providerName, mockLocation);
        }

1 个答案:

答案 0 :(得分:0)

当您的代码侦听位置更新时,您应该同时模拟该位置。

在您的情况下,无论何时调用pushLocation方法,都会触发onLocationChanged方法。

正在侦听gps

 @Override
public void onLocationChanged(Location Loc) {
    double lat = Loc.getLatitude();
    double lon = Loc.getLongitude();
    String l = "Longitude: " + lon + " Latitude: " + lat;
    Toast.makeText(getApplicationContext(), l ,Toast.LENGTH_SHORT).show();
}

来模拟它

Handler mHandler = new Handler();
public void loopMock(){
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // onLocationChanged method will be fired
            mock.pushLocation(-12.34, 23.45);
            mHandler.postDelayed(this, 1000);
        }
    }, 1000);
}