【发布时间】:2015-08-27 15:42:09
【问题描述】:
这是我的代码:
public class MockLocationHelper {
private String providerName ;
private Context context;
private LocationManager locationManager ;
MockLocationHelper(String providerName, Context context){
this.providerName = providerName;
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
locationManager.addTestProvider(providerName, true, true, true, false, false, false, false, 1, 2);
locationManager.setTestProviderEnabled(providerName, true);
}catch(SecurityException e){
Log.d(TAG, "SecurityException : MockLocationHelper()");
e.printStackTrace();
}catch(IllegalArgumentException e){
Log.d(TAG, "IllegalArgumentException : MockLocationHelper()");
e.printStackTrace();
}
}
public void startMocking(String latitude, String longitude) {
Location location = new Location(providerName);
location.setLatitude(Double.parseDouble(latitude));
location.setLongitude(Double.parseDouble(longitude));
location.setAltitude(0);
location.setAccuracy(2);
location.setTime(System.currentTimeMillis());
location.setElapsedRealtimeNanos(System.nanoTime());
try {
locationManager.setTestProviderLocation(providerName, location);
}catch(SecurityException e){
Log.d(TAG, "SecurityException : startMocking()");
e.printStackTrace();
}catch(IllegalArgumentException e){
Log.d(TAG, "IllegalArgumentException : startMocking()");
e.printStackTrace();
}
}
public void stopMocking(){
try{
locationManager.removeTestProvider(providerName);
}catch(SecurityException e){
Log.d(TAG, "SecurityException : stopMocking()");
e.printStackTrace();
}catch(IllegalArgumentException e){
Log.d(TAG, "IllegalArgumentException : stopMocking()");
e.printStackTrace();
}
}
}
这里是 onCreate() 函数:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText latitude = (EditText) findViewById(R.id.latitude);
final EditText longitude = (EditText) findViewById(R.id.longitude);
Location location = new Location(LocationManager.PASSIVE_PROVIDER);
location.setLatitude(Double.parseDouble(latitude.getText().toString()));
location.setLongitude(Double.parseDouble(longitude.getText().toString()))
final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MockLocationHelper mockLocationHelper = new MockLocationHelper(LocationManager.PASSIVE_PROVIDER, this);
mockLocationHelper.startMocking(latitude.getText().toString(), longitude.getText().toString());
mockLocationHelper.stopMocking();
latitude.setText("");
longitude.setText("");
}
运行此代码时,它会给出 IllegalAregumentException : "passive" provider unknown。 如果我们将 provider 替换为 GPS_PROVIDER 或 NETWORK_PROVIDER,则此代码可以正常工作。
清单权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
开发者控制台中启用了模拟选项,我正在 Kitkat 上运行应用程序。为什么我会收到此异常,我应该如何模拟被动位置?
【问题讨论】:
-
你能把你的整个错误贴出来