Android mock location on device?

2019-01-01 17:02发布

How can I mock my location on a physical device (Nexus One)? I know you can do this with the emulator in the Emulator Control panel, but this doesn't work for a physical device.

19条回答
还给你的自由
2楼-- · 2019-01-01 17:45

This worked for me (Android Studio):

Disable GPS and WiFi tracking on the phone. On Android 5.1.1 and below, select "enable mock locations" in Developer Options.

Make a copy of your manifest in the src/debug directory. Add the following to it (outside of the "application" tag):

uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"

Set up a map Fragment called "map". Include the following code in onCreate():

lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new MyLocationListener();
if (lm.getProvider("Test") == null) {
    lm.addTestProvider("Test", false, false, false, false, false, false, false, 0, 1);
}
lm.setTestProviderEnabled("Test", true);
lm.requestLocationUpdates("Test", 0, 0, ll);

map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
    @Override
    public void onMapClick(LatLng l) {
        Location loc = new Location("Test");
        loc.setLatitude(l.latitude);
        loc.setLongitude(l.longitude);
        loc.setAltitude(0); 
        loc.setAccuracy(10f);
        loc.setElapsedRealtimeNanos(System.nanoTime());
        loc.setTime(System.currentTimeMillis()); 
        lm.setTestProviderLocation("Test", loc);
    }
};

Note that you may have to temporarily increase "minSdkVersion" in your module gradle file to 17 in order to use the "setElapsedRealtimeNanos" method.

Include the following code inside the main activity class:

private class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        // do whatever you want, scroll the map, etc.
    }
}

Run your app with AS. On Android 6.0 and above you will get a security exception. Now go to Developer Options in Settings and select "Select mock location app". Select your app from the list.

Now when you tap on the map, onLocationChanged() will fire with the coordinates of your tap.

I just figured this out so now I don't have to tramp around the neighborhood with phones in hand.

查看更多
登录 后发表回答