在安卓设备上模拟位置
Posted
技术标签:
【中文标题】在安卓设备上模拟位置【英文标题】:Mocking location on android device 【发布时间】:2017-01-19 22:28:56 【问题描述】:我正在尝试测试使用 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】:当您的代码监听位置更新时,您应该同时模拟位置。
在您的情况下,每当您调用 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);
【讨论】:
以上是关于在安卓设备上模拟位置的主要内容,如果未能解决你的问题,请参考以下文章