Testing GPS in Android

后端 未结 6 592
-上瘾入骨i
-上瘾入骨i 2020-12-07 23:38

How do you test GPS applications in Android? Can we test it using the Android emulator?

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 00:04

    in addition to Mallox code this is the sulotion for mock location in addition to real gps location : TEST_MOCK_GPS_LOCATION is a string

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = null;
    
        List providers = lm.getAllProviders();
        for (Object provider : providers) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            Location loc = lm.getLastKnownLocation((String) provider);
            if  (provider.equals(TEST_MOCK_GPS_LOCATION))  {
                mLastLocation = loc;
            }
        } 
    

    in the test class it is :

    public class GPSPollingServiceTest extends AndroidTestCase {
    private LocationManager locationManager;
    
    public void testGPS() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        LocationManager locationManager = (LocationManager) this.getContext().getSystemService(Context.LOCATION_SERVICE);
        List providers = locationManager.getAllProviders();
        if(!providers.contains(TEST_MOCK_GPS_LOCATION)) {
            locationManager.addTestProvider(TEST_MOCK_GPS_LOCATION, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
            locationManager.setTestProviderEnabled(TEST_MOCK_GPS_LOCATION, true);
            // Set up your test
            Location location = new Location(TEST_MOCK_GPS_LOCATION);
            location.setLatitude(34.1233400);
            location.setLongitude(15.6777880);
            location.setAccuracy(7);
            location.setTime(8);
            location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    
            locationManager.setTestProviderLocation(TEST_MOCK_GPS_LOCATION, location);
    
            Method locationJellyBeanFixMethod = Location.class.getMethod("makeComplete");
            if (locationJellyBeanFixMethod != null) {
                locationJellyBeanFixMethod.invoke(location);
            }
        } else {
            // Check if your listener reacted the right way
            locationManager.removeTestProvider(TEST_MOCK_GPS_LOCATION);
        }
    }
    

    }

    hope it will help you

提交回复
热议问题