模拟位置时未调用onLocationChanged()

时间:2015-01-09 12:34:29

标签: android

我无法在真实设备上发送模拟位置。我已在设置中启用模拟位置,并在位置设置中禁用了网络位置。

清单:

 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

以下是代码:

private static final String PROVIDER_NAME = "flp";
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.setTestProviderEnabled(PROVIDER_NAME, true);
locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 1000, 1, new LocationListener() {
                            @Override
                            public void onLocationChanged(Location location) {

                            }

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) {

                            }

                            @Override
                            public void onProviderEnabled(String provider) {

                            }

                            @Override
                            public void onProviderDisabled(String provider) {

                            }
                        });

                mockLocation(12.333, 13.444);

这个方法:

public void mockLocation(double lat, double lng) {
        // Create a new Location
        Location newLocation = new Location(PROVIDER_NAME);
        newLocation.setLatitude(lat);
        newLocation.setLongitude(lng);
        newLocation.setAccuracy(3.0f);
        newLocation.setTime(1);
        locationManager.setTestProviderLocation(PROVIDER_NAME, newLocation);
    }

为什么没有调用onLocationChanged()?

1 个答案:

答案 0 :(得分:1)

这对我有用

locationManager.addTestProvider(mocLocationProvider, false, false,
                    false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);


Location mockLocation = new Location(mocLocationProvider); // a string
mockLocation.setLatitude(location.getLatitude());  // double 
mockLocation.setLongitude(location.getLongitude()); 
mockLocation.setAltitude(location.getAltitude()); 
mockLocation.setTime(System.currentTimeMillis()); 
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation); 



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

同样在Android手机设置中,请确保勾选“允许模拟位置”复选框。

Source