Advertisement
icyerasor

Android MockLocation

Apr 15th, 2011
2,461
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class MockLocationUtil {
  2. public static final String PROVIDER NAME = "testProvider";
  3.   public static void publishMockLocation(double latitude, double longitude, Context ctx) {
  4.     LocationManager mLocationManager = (LocationManager) ctx.getSystemService(Service.LOCATION_SERVICE);
  5.     for (String prov : mLocationManager.getAllProviders()) {
  6.       Log.w(TAG, prov);
  7.     }
  8.     if (mLocationManager.getProvider(PROVIDER_NAME) != null) {
  9.       Log.w(TAG, "Removing provider " + PROVIDER_NAME);
  10.       mLocationManager.removeTestProvider(PROVIDER_NAME);
  11.     }
  12.     for (String prov : mLocationManager.getAllProviders()) {
  13.       Log.w(TAG, prov);
  14.     }
  15.  
  16.     if (mLocationManager.getProvider(PROVIDER_NAME) == null) {
  17.       Log.w(TAG, "Adding provider " + PROVIDER_NAME + " again");
  18.       mLocationManager.addTestProvider(PROVIDER_NAME, "requiresNetwork" == "", "requiresSatellite" == "",
  19.           "requiresCell" == "", "hasMonetaryCost" == "", "supportsAltitude" == "", "supportsSpeed" == "",
  20.           "supportsBearing" == "", android.location.Criteria.POWER_LOW, android.location.Criteria.ACCURACY_FINE);
  21.     }
  22.     for (String prov : mLocationManager.getAllProviders()) {
  23.       Log.w(TAG, prov);
  24.     }
  25.  
  26.     Location newLocation = new Location(PROVIDER_NAME);
  27.  
  28.     newLocation.setLatitude(latitude);
  29.     newLocation.setLongitude(longitude);
  30.     newLocation.setTime(System.currentTimeMillis());
  31.     newLocation.setAccuracy(25);
  32.  
  33.     mLocationManager.setTestProviderEnabled(PROVIDER_NAME, true);
  34.  
  35.     mLocationManager.setTestProviderStatus(PROVIDER_NAME, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
  36.  
  37.     mLocationManager.requestLocationUpdates(PROVIDER_NAME, 0, 0, new MockLocationListener());
  38.  
  39.     mLocationManager.setTestProviderLocation(PROVIDER_NAME, newLocation);
  40.     Log.w(TAG, "published location: " + newLocation);
  41.  
  42.     Log.w(TAG, "LastKnownLocation of "+PROVIDER_NAME+" is: "+mLocationManager.getLastKnownLocation(PROVIDER_NAME));
  43.   }
  44.  
  45. public Location getLastKnownLocationInApplication(Context ctx) {
  46. Location testLoc;
  47. LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
  48.  
  49. if (lm.getAllProviders().contains(PROVIDER_NAME)) {
  50.       testLoc = lm.getLastKnownLocation(PROVIDER_NAME);
  51.       Log.d(TAG, "TestLocation: " + testLoc);
  52.     }
  53.  
  54. Location realLoc = lm.getLastKnownLocation();
  55.  
  56. if(testLoc != null) {
  57.   return testLoc;
  58. } else {
  59.   return realLoc;
  60. }
  61. }
Advertisement
RAW Paste Data Copied
Advertisement