Java Code Examples for android.location.Location#setTime()

The following examples show how to use android.location.Location#setTime() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocationProvider.java    From privatelocation with GNU General Public License v3.0 7 votes vote down vote up
void pushLocation(double lat, double lon) {
    LocationManager locationManager = (LocationManager) context.getSystemService(
            Context.LOCATION_SERVICE);

    Location mockLocation = new Location(providerName);
    mockLocation.setLatitude(lat);
    mockLocation.setLongitude(lon);
    mockLocation.setAltitude(3F);
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setSpeed(0.01F);
    mockLocation.setBearing(1F);
    mockLocation.setAccuracy(3F);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mockLocation.setBearingAccuracyDegrees(0.1F);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mockLocation.setVerticalAccuracyMeters(0.1F);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mockLocation.setSpeedAccuracyMetersPerSecond(0.01F);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    locationManager.setTestProviderLocation(providerName, mockLocation);
}
 
Example 2
Source File: SearchEngineTest.java    From mytracks with Apache License 2.0 7 votes vote down vote up
private long insertWaypoint(String title, String description, String category, double distance, long hoursAgo, long trackId) {
  Waypoint waypoint = new Waypoint();
  waypoint.setName(title);
  waypoint.setDescription(description);
  waypoint.setCategory(category);
  waypoint.setTrackId(trackId);

  Location location = new Location(HERE);
  location.setLatitude(location.getLatitude() + distance);
  location.setLongitude(location.getLongitude() + distance);
  if (hoursAgo >= 0) {
    location.setTime(NOW - hoursAgo * 1000L * 60L * 60L);
  }
  waypoint.setLocation(location);

  Uri uri = providerUtils.insertWaypoint(waypoint);
  return ContentUris.parseId(uri);
}
 
Example 3
Source File: NmeaParser.java    From contrib-drivers with Apache License 2.0 6 votes vote down vote up
private void postLocation(long timestamp, double latitude, double longitude, double altitude, float speed, float bearing) {
    if (mGpsModuleCallback != null) {
        Location location = new Location(LocationManager.GPS_PROVIDER);
        // We cannot compute accuracy from NMEA data alone.
        // Assume that a valid fix has the quoted accuracy of the module.
        // Framework requires accuracy in DRMS.
        location.setAccuracy(mGpsAccuracy * 1.2f);
        location.setTime(timestamp);

        location.setLatitude(latitude);
        location.setLongitude(longitude);
        if (altitude != -1) {
            location.setAltitude(altitude);
        }
        if (speed != -1) {
            location.setSpeed(speed);
        }
        if (bearing != -1) {
            location.setBearing(bearing);
        }

        mGpsModuleCallback.onGpsLocationUpdate(location);
    }
}
 
Example 4
Source File: AbstractFileTrackImporter.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a location.
 * 
 * @param latitudeValue the latitude value
 * @param longitudeValue the longitude value
 * @param altitudeValue the altitude value
 * @param timeValue the time value
 */
private Location createLocation(
    double latitudeValue, double longitudeValue, Double altitudeValue, long timeValue) {
  Location location = new Location(LocationManager.GPS_PROVIDER);
  location.setLatitude(latitudeValue);
  location.setLongitude(longitudeValue);
  if (altitudeValue != null) {
    location.setAltitude(altitudeValue);      
  } else {
    location.removeAltitude();
  }
  location.setTime(timeValue);
  location.removeAccuracy();
  location.removeBearing();
  location.removeSpeed();
  return location;
}
 
Example 5
Source File: LocationHooker.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
@Override
public Object onInvoke(Object originObject, Object proxyObject, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
    if (!GpsMockManager.getInstance().isMocking()) {
        return method.invoke(originObject, args);
    }
    Location lastLocation = (Location) method.invoke(originObject, args);
    if (lastLocation == null) {
        lastLocation = buildValidLocation(null);
    }
    lastLocation.setLongitude(GpsMockManager.getInstance().getLongitude());
    lastLocation.setLatitude(GpsMockManager.getInstance().getLatitude());
    lastLocation.setTime(System.currentTimeMillis());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        lastLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    return lastLocation;
}
 
Example 6
Source File: LocationService.java    From FineGeotag with GNU General Public License v3.0 6 votes vote down vote up
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jObject = (JsonObject) json;
    Location location = new Location(jObject.get("Provider").getAsString());

    location.setTime(jObject.get("Time").getAsLong());
    location.setLatitude(jObject.get("Latitude").getAsDouble());
    location.setLongitude(jObject.get("Longitude").getAsDouble());

    if (jObject.has("Altitude"))
        location.setAltitude(jObject.get("Altitude").getAsDouble());

    if (jObject.has("Speed"))
        location.setSpeed(jObject.get("Speed").getAsFloat());

    if (jObject.has("Bearing"))
        location.setBearing(jObject.get("Bearing").getAsFloat());

    if (jObject.has("Accuracy"))
        location.setAccuracy(jObject.get("Accuracy").getAsFloat());

    return location;
}
 
Example 7
Source File: BackgroundLocation.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
/**
 * Return android Location instance
 *
 * @return android.location.Location instance
 */
public Location getLocation() {
    Location l = new Location(provider);
    l.setLatitude(latitude);
    l.setLongitude(longitude);
    l.setTime(time);
    if (hasAccuracy) l.setAccuracy(accuracy);
    if (hasAltitude) l.setAltitude(altitude);
    if (hasSpeed) l.setSpeed(speed);
    if (hasBearing) l.setBearing(bearing);
    l.setExtras(extras);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        l.setElapsedRealtimeNanos(elapsedRealtimeNanos);
    }

    return l;
}
 
Example 8
Source File: MainActivity.java    From together-go with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void setLocation(double longtitude, double latitude) {

        // 因为我是在北京的,我把这个海拔设置了一个符合北京的范围,随机生成
        altitude = genDouble(38.0, 50.5);
        // 而定位有精度,GPS精度一般小于15米,我设置在1到15米之间随机
        accuracy = (float)genDouble(1.0, 15.0);

        // 下面就是自己设置定位的位置了
        Location location = new Location(LocationManager.GPS_PROVIDER);
        location.setTime(System.currentTimeMillis());
        location.setLatitude(latitude);
        location.setLongitude(longtitude);
        // 北京海拔大概范围,随机生成
        location.setAltitude(altitude);
        // GPS定位精度范围,随机生成
        location.setAccuracy(accuracy);
        if (Build.VERSION.SDK_INT > 16) {
            location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
        }
        try {
            locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, location);
        } catch (SecurityException e) {
            simulateLocationPermission();
        }
    }
 
Example 9
Source File: DataUploadServiceTest.java    From open with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldHaveSpeedElement() throws Exception {
    String expectedSpeed = "40.0";
    String groupId = "test-group-id";
    String routeId = "test-route-id";
    fillLocationsTable(groupId, routeId, 10, true);
    Location loc = getTestLocation(100, 200);
    loc.setBearing(4.0f);
    loc.setSpeed(Float.valueOf(expectedSpeed));
    loc.setAccuracy(12f);
    loc.setAltitude(12f);
    loc.setTime(System.currentTimeMillis());
    ContentValues insertValues = valuesForLocationCorrection(loc, loc, getTestInstruction(0, 0),
        routeId);
    db.insert(TABLE_LOCATIONS, null, insertValues);

    String actual = getTextForXpath(groupId,
            "//trk/trkseg/trkpt[position()=last()]/speed/text()");

    assertThat(actual).isEqualTo(expectedSpeed);
}
 
Example 10
Source File: ReplayRouteLocationConverter.java    From graphhopper-navigation-android with MIT License 5 votes vote down vote up
private Location createMockLocationFrom(Point point) {
  Location mockedLocation = new Location(REPLAY_ROUTE);
  mockedLocation.setLatitude(point.latitude());
  mockedLocation.setLongitude(point.longitude());
  float speedInMetersPerSec = (float) ((speed * ONE_KM_IN_METERS) / ONE_HOUR_IN_SECONDS);
  mockedLocation.setSpeed(speedInMetersPerSec);
  mockedLocation.setAccuracy(3f);
  mockedLocation.setTime(time);
  return mockedLocation;
}
 
Example 11
Source File: LocationSubjectTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void isEqualTo() {
  Location location = new Location(LocationManager.GPS_PROVIDER);
  location.setLatitude(1);
  location.setLongitude(-1);
  location.setTime(2);

  Location other = new Location(location);

  assertThat(location).isEqualTo(other);

  assertThat((Location) null).isEqualTo(null);
}
 
Example 12
Source File: SQLiteLocationDAOTest.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
@Test
public void persistLocation() {
    Context ctx = InstrumentationRegistry.getTargetContext();
    SQLiteDatabase db = new SQLiteOpenHelper(ctx).getWritableDatabase();
    SQLiteLocationDAO dao = new SQLiteLocationDAO(db);

    Location location = new Location("fake");
    location.setAccuracy(200);
    location.setAltitude(900);
    location.setBearing(2);
    location.setLatitude(40.21);
    location.setLongitude(23.45);
    location.setSpeed(20);
    location.setProvider("test");
    location.setTime(1000);
    BackgroundLocation bgLocation = new BackgroundLocation(location);

    dao.persistLocation(bgLocation);

    ArrayList<BackgroundLocation> locations = new ArrayList(dao.getAllLocations());
    Assert.assertEquals(1, locations.size());

    BackgroundLocation storedLocation = locations.get(0);
    Assert.assertEquals(200, storedLocation.getAccuracy(), 0);
    Assert.assertEquals(900, storedLocation.getAltitude(), 0);
    Assert.assertEquals(2, storedLocation.getBearing(), 0);
    Assert.assertEquals(40.21, storedLocation.getLatitude(), 0);
    Assert.assertEquals(23.45, storedLocation.getLongitude(), 0);
    Assert.assertEquals(20, storedLocation.getSpeed(), 0);
    Assert.assertEquals("test", storedLocation.getProvider(), "test");
    Assert.assertEquals(1000, storedLocation.getTime(), 0);
    Assert.assertFalse(storedLocation.hasMockLocationsEnabled());
    Assert.assertFalse(storedLocation.areMockLocationsEnabled());
    Assert.assertTrue(storedLocation.hasIsFromMockProvider()); // because setIsFromMockProvider is called in constructor
    Assert.assertFalse(storedLocation.isFromMockProvider());
}
 
Example 13
Source File: GpsMocker.java    From AutoInteraction-Library with Apache License 2.0 5 votes vote down vote up
private void scheduleMockGps(final Context context) {
    Gps gps;
    synchronized (mMockGps) {
        gps = mMockGps[0];
    }
    if (null == gps) {
        return;
    }
    if (!Macro.RealGps) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location location = new Location(LocationManager.GPS_PROVIDER);
        location.setLatitude(gps.mLatitude);
        location.setLongitude(gps.mLongitude);
        location.setAltitude(0);
        location.setBearing(0);
        location.setSpeed(0);
        location.setAccuracy(2);
        location.setTime(System.currentTimeMillis());
        location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
        locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, location);
    }
    new Handler(context.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            scheduleMockGps(context);
        }
    }, 1000);
}
 
Example 14
Source File: MyTracksProviderUtilsImpl.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Fills a track point from a cursor.
 * 
 * @param cursor the cursor pointing to a location.
 * @param indexes the cached track points indexes
 * @param location the track point
 */
private void fillTrackPoint(Cursor cursor, CachedTrackPointsIndexes indexes, Location location) {
  location.reset();

  if (!cursor.isNull(indexes.longitudeIndex)) {
    location.setLongitude(((double) cursor.getInt(indexes.longitudeIndex)) / 1E6);
  }
  if (!cursor.isNull(indexes.latitudeIndex)) {
    location.setLatitude(((double) cursor.getInt(indexes.latitudeIndex)) / 1E6);
  }
  if (!cursor.isNull(indexes.timeIndex)) {
    location.setTime(cursor.getLong(indexes.timeIndex));
  }
  if (!cursor.isNull(indexes.altitudeIndex)) {
    location.setAltitude(cursor.getFloat(indexes.altitudeIndex));
  }
  if (!cursor.isNull(indexes.accuracyIndex)) {
    location.setAccuracy(cursor.getFloat(indexes.accuracyIndex));
  }
  if (!cursor.isNull(indexes.speedIndex)) {
    location.setSpeed(cursor.getFloat(indexes.speedIndex));
  }
  if (!cursor.isNull(indexes.bearingIndex)) {
    location.setBearing(cursor.getFloat(indexes.bearingIndex));
  }
  if (location instanceof MyTracksLocation && !cursor.isNull(indexes.sensorIndex)) {
    MyTracksLocation myTracksLocation = (MyTracksLocation) location;
    try {
      myTracksLocation.setSensorDataSet(
          SensorDataSet.parseFrom(cursor.getBlob(indexes.sensorIndex)));
    } catch (InvalidProtocolBufferException e) {
      Log.w(TAG, "Failed to parse sensor data.", e);
    }
  }
}
 
Example 15
Source File: MockLocationProvider.java    From mockgeofix with Apache License 2.0 5 votes vote down vote up
protected void _simulate(double longitude, double latitude, double altitude, int satellites) {
    Location mockLocation = new Location(locationProviderName); // a string
    mockLocation.setLatitude(latitude);  // double
    mockLocation.setLongitude(longitude);
    mockLocation.setAltitude(altitude);
    if (satellites != -1) {
        Bundle bundle = new Bundle();
        bundle.putInt("satellites", satellites);
        mockLocation.setExtras(bundle);
    }
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setAccuracy(accuracy);
    _simulate(mockLocation);
}
 
Example 16
Source File: CameraMetadataNative.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private Location getGpsLocation() {
    String processingMethod = get(CaptureResult.JPEG_GPS_PROCESSING_METHOD);
    double[] coords = get(CaptureResult.JPEG_GPS_COORDINATES);
    Long timeStamp = get(CaptureResult.JPEG_GPS_TIMESTAMP);

    if (areValuesAllNull(processingMethod, coords, timeStamp)) {
        return null;
    }

    Location l = new Location(translateProcessToLocationProvider(processingMethod));
    if (timeStamp != null) {
        // Location expects timestamp in [ms.]
        l.setTime(timeStamp * 1000);
    } else {
        Log.w(TAG, "getGpsLocation - No timestamp for GPS location.");
    }

    if (coords != null) {
        l.setLatitude(coords[0]);
        l.setLongitude(coords[1]);
        l.setAltitude(coords[2]);
    } else {
        Log.w(TAG, "getGpsLocation - No coordinates for GPS location");
    }

    return l;
}
 
Example 17
Source File: GpsMocker.java    From AutoInteraction-Library with Apache License 2.0 5 votes vote down vote up
private void scheduleMockGps(final Context context) {
    Gps gps;
    synchronized (mMockGps) {
        gps = mMockGps[0];
    }
    if (null == gps) {
        return;
    }
    if (!Macro.RealGps) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location location = new Location(LocationManager.GPS_PROVIDER);
        location.setLatitude(gps.mLatitude);
        location.setLongitude(gps.mLongitude);
        location.setAltitude(0);
        location.setBearing(0);
        location.setSpeed(0);
        location.setAccuracy(2);
        location.setTime(System.currentTimeMillis());
        location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
        locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, location);
    }
    new Handler(context.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            scheduleMockGps(context);
        }
    }, 1000);
}
 
Example 18
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
private void handleConnectivity(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Update weather/pressure
    long ref_time = prefs.getLong(SettingsFragment.PREF_PRESSURE_REF_TIME, 0);
    int weatherInterval = Integer.parseInt(prefs.getString(SettingsFragment.PREF_WEATHER_INTERVAL, SettingsFragment.DEFAULT_WEATHER_INTERVAL));

    if (ref_time + 60 * 1000L * weatherInterval < new Date().getTime()) {
        Intent intentWeather = new Intent(this, BackgroundService.class);
        intentWeather.setAction(BackgroundService.ACTION_UPDATE_WEATHER);
        startService(intentWeather);
    }

    boolean metered = Util.isMeteredNetwork(this);
    long last = prefs.getLong(SettingsFragment.PREF_LIFELINE_LAST, 0);
    int interval = Integer.parseInt(prefs.getString(SettingsFragment.PREF_LIFELINE_METERED_INTERVAL, SettingsFragment.DEFAULT_LIFELINE_METERED_INTERVAL));
    if (!metered || interval == 0 || last + 60 * 1000L * interval < new Date().getTime()) {
        Log.i(TAG, "Lifeline update metered=" + metered + " interval=" + interval);

        // Update lifeline
        if (prefs.getBoolean(SettingsFragment.PREF_LIFELINE_ENABLED, SettingsFragment.DEFAULT_LIFELINE_ENABLED))
            try {
                DatabaseHelper dh = null;
                Cursor cursor = null;
                try {
                    dh = new DatabaseHelper(this);
                    cursor = dh.getUnsentLocations();

                    int colID = cursor.getColumnIndex("ID");
                    int colTime = cursor.getColumnIndex("time");
                    int colProvider = cursor.getColumnIndex("provider");
                    int colLatitude = cursor.getColumnIndex("latitude");
                    int colLongitude = cursor.getColumnIndex("longitude");
                    int colAltitude = cursor.getColumnIndex("altitude");
                    int colAccuracy = cursor.getColumnIndex("accuracy");
                    int colName = cursor.getColumnIndex("name");
                    int colDeleted = cursor.getColumnIndex("deleted");

                    while (Util.isConnected(this) && (!Util.isMeteredNetwork(this) || interval == 0) && cursor.moveToNext()) {
                        long id = cursor.getLong(colID);
                        String name = cursor.getString(colName);

                        Location location = new Location(cursor.getString(colProvider));
                        location.setTime(cursor.isNull(colDeleted) ? cursor.getLong(colTime) : Long.MAX_VALUE);
                        location.setLatitude(cursor.getDouble(colLatitude));
                        location.setLongitude(cursor.getDouble(colLongitude));
                        if (!cursor.isNull(colAltitude))
                            location.setAltitude(cursor.getDouble(colAltitude));
                        if (!cursor.isNull(colAccuracy))
                            location.setAccuracy(cursor.getFloat(colAccuracy));

                        postLocation(id, location, name);
                    }
                    Log.i(TAG, "All locations sent=" + cursor.isAfterLast());
                } finally {
                    if (cursor != null)
                        cursor.close();
                    if (dh != null)
                        dh.close();
                }
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
    }
}
 
Example 19
Source File: BackendService.java    From wifi_backend with GNU General Public License v3.0 4 votes vote down vote up
private Location wiFiBasedLocation(@NonNull List<WifiAccessPoint> accessPoints) {
    if (accessPoints.isEmpty()) {
        return null;
    } else {
        Set<Location> locations = new HashSet<>(accessPoints.size());

        for (WifiAccessPoint accessPoint : accessPoints) {
            SimpleLocation result = database.getLocation(accessPoint.rfId());

            if (result != null) {
                Bundle extras = new Bundle();
                extras.putInt(Configuration.EXTRA_SIGNAL_LEVEL, accessPoint.level());

                Location location = result.toAndroidLocation();
                location.setExtras(extras);
                locations.add(location);
            }
        }

        if (locations.isEmpty()) {
            if (DEBUG) {
                Log.i(TAG, "WifiDBResolver.process(): No APs with known locations");
            }
            return null;
        } else {
            // Find largest group of AP locations. If we don't have at
            // least two near each other then we don't have enough
            // information to get a good location.
            locations = LocationUtil.culledAPs(locations, BackendService.this);

            if (locations == null || locations.size() < 2) {
                if (DEBUG) {
                    Log.i(TAG, "WifiDBResolver.process(): Insufficient number of WiFi hotspots to resolve location");
                }
                return null;
            } else {
                Location avgLoc = LocationUtil.weightedAverage("wifi", locations);

                if (avgLoc == null) {
                    if (DEBUG) {
                        Log.e(TAG, "Averaging locations did not work.");
                    }
                    return null;
                } else {
                    avgLoc.setTime(System.currentTimeMillis());
                    return avgLoc;
                }
            }
        }
    }
}
 
Example 20
Source File: FileTrackExporter.java    From mytracks with Apache License 2.0 2 votes vote down vote up
/**
 * Sets a location time.
 * 
 * @param location the location
 * @param offset the time offset
 */
private void setLocationTime(Location location, long offset) {
  if (location != null) {
    location.setTime(location.getTime() - offset);
  }
}