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

The following examples show how to use android.location.Location#getElapsedRealtimeNanos() . 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: GeofenceManager.java    From android_9.0.0_r45 with Apache License 2.0 7 votes vote down vote up
/**
 * Returns the location received most recently from {@link #onLocationChanged(Location)},
 * or consult {@link LocationManager#getLastLocation()} if none has arrived. Does not return
 * either if the location would be too stale to be useful.
 *
 * @return a fresh, valid Location, or null if none is available
 */
private Location getFreshLocationLocked() {
    // Prefer mLastLocationUpdate to LocationManager.getLastLocation().
    Location location = mReceivingLocationUpdates ? mLastLocationUpdate : null;
    if (location == null && !mFences.isEmpty()) {
        location = mLocationManager.getLastLocation();
    }

    // Early out for null location.
    if (location == null) {
        return null;
    }

    // Early out for stale location.
    long now = SystemClock.elapsedRealtimeNanos();
    if (now - location.getElapsedRealtimeNanos() > MAX_AGE_NANOS) {
        return null;
    }

    // Made it this far? Return our fresh, valid location.
    return location;
}
 
Example 2
Source File: LocationBasedCountryDetector.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * @return the last known location from all providers
 */
protected Location getLastKnownLocation() {
    final long bid = Binder.clearCallingIdentity();
    try {
        List<String> providers = mLocationManager.getAllProviders();
        Location bestLocation = null;
        for (String provider : providers) {
            Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider);
            if (lastKnownLocation != null) {
                if (bestLocation == null ||
                        bestLocation.getElapsedRealtimeNanos() <
                        lastKnownLocation.getElapsedRealtimeNanos()) {
                    bestLocation = lastKnownLocation;
                }
            }
        }
        return bestLocation;
    } finally {
        Binder.restoreCallingIdentity(bid);
    }
}
 
Example 3
Source File: BackgroundLocation.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
public static BackgroundLocation fromLocation(Location location) {
    BackgroundLocation l = new BackgroundLocation();

    l.provider = location.getProvider();
    l.latitude = location.getLatitude();
    l.longitude = location.getLongitude();
    l.time = location.getTime();
    l.accuracy = location.getAccuracy();
    l.speed = location.getSpeed();
    l.bearing = location.getBearing();
    l.altitude = location.getAltitude();
    l.hasAccuracy = location.hasAccuracy();
    l.hasAltitude = location.hasAltitude();
    l.hasSpeed = location.hasSpeed();
    l.hasBearing = location.hasBearing();
    l.extras = location.getExtras();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        l.elapsedRealtimeNanos = location.getElapsedRealtimeNanos();
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        l.setIsFromMockProvider(location.isFromMockProvider());
    }

    return l;
}
 
Example 4
Source File: TwilightScanner.java    From PhoneProfilesPlus with Apache License 2.0 6 votes vote down vote up
private static boolean hasMoved(Location from, Location to) {
    if (to == null) {
        return false;
    }

    if (from == null) {
        return true;
    }

    // if new location is older than the current one, the device hasn't moved.
    if (to.getElapsedRealtimeNanos() < from.getElapsedRealtimeNanos()) {
        return false;
    }

    // Get the distance between the two points.
    float distance = from.distanceTo(to);

    // Get the total accuracy radius for both locations.
    float totalAccuracy = from.getAccuracy() + to.getAccuracy();

    // If the distance is greater than the combined accuracy of the two
    // points then they can't overlap and hence the user has moved.
    return distance >= totalAccuracy;
}
 
Example 5
Source File: LocationManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static boolean shouldBroadcastSafe(
        Location loc, Location lastLoc, UpdateRecord record, long now) {
    // Always broadcast the first update
    if (lastLoc == null) {
        return true;
    }

    // Check whether sufficient time has passed
    long minTime = record.mRealRequest.getFastestInterval();
    long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
            / NANOS_PER_MILLI;
    if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
        return false;
    }

    // Check whether sufficient distance has been traveled
    double minDistance = record.mRealRequest.getSmallestDisplacement();
    if (minDistance > 0.0) {
        if (loc.distanceTo(lastLoc) <= minDistance) {
            return false;
        }
    }

    // Check whether sufficient number of udpates is left
    if (record.mRealRequest.getNumUpdates() <= 0) {
        return false;
    }

    // Check whether the expiry date has passed
    return record.mRealRequest.getExpireAt() >= now;
}
 
Example 6
Source File: LocationUpdateService.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
private long getLocationTimeInMilis(Location location) {
    if (location == null) {
        return 0;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
         return System.currentTimeMillis()
            - SystemClock.elapsedRealtime()
            + (location.getElapsedRealtimeNanos() / 1000000);
    } else {
        return location.getTime();
    }

}
 
Example 7
Source File: DeviceLocation.java    From ARCore-Location with MIT License 5 votes vote down vote up
private long getLocationAge(Location newLocation) {
    long locationAge;
    if (android.os.Build.VERSION.SDK_INT >= 17) {
        long currentTimeInMilli = (long) (SystemClock.elapsedRealtimeNanos() / 1000000);
        long locationTimeInMilli = (long) (newLocation.getElapsedRealtimeNanos() / 1000000);
        locationAge = currentTimeInMilli - locationTimeInMilli;
    } else {
        locationAge = System.currentTimeMillis() - newLocation.getTime();
    }
    return locationAge;
}
 
Example 8
Source File: LocationDataCollector.java    From DataLogger with MIT License 5 votes vote down vote up
@Override
    public void onLocationChanged(Location location) {

        if (location == null) return;

        // Return the time of this fix, in elapsed real-time since system boot.
        long locationNanoTime = location.getElapsedRealtimeNanos() + mNanosOffset;

        // System local time in millis
        long currentMillis = (new Date()).getTime();

        // Get the estimated accuracy of this location, in meters.
        float accuracy = location.getAccuracy();

        // Get the latitude, in degrees.
        double latitude = location.getLatitude();

        // Get the longitude, in degrees.
        double longitude = location.getLongitude();

        // Get the altitude if available, in meters above the WGS 84 reference ellipsoid.
        double altitude = location.getAltitude();

        String message = String.format("%s", currentMillis) + ";"
                + String.format("%s", locationNanoTime) + ";"
                + String.format("%s", mNanosOffset) + ";"
                + accuracy + ";"
                + latitude + ";"
                + longitude + ";"
                + altitude;

//        // Get the latitude, in degrees.
//        String latitudeDegrees = Location.convert(latitude, Location.FORMAT_DEGREES);
//        // Get the longitude, in degrees.
//        String longitudeDegrees = Location.convert(longitude, Location.FORMAT_DEGREES);

        logger.log(message);
        logger.log(System.lineSeparator());
    }
 
Example 9
Source File: LocationService.java    From AndroidLocationStarterKit with MIT License 5 votes vote down vote up
@SuppressLint("NewApi")
private long getLocationAge(Location newLocation){
    long locationAge;
    if(android.os.Build.VERSION.SDK_INT >= 17) {
        long currentTimeInMilli = (long)(SystemClock.elapsedRealtimeNanos() / 1000000);
        long locationTimeInMilli = (long)(newLocation.getElapsedRealtimeNanos() / 1000000);
        locationAge = currentTimeInMilli - locationTimeInMilli;
    }else{
        locationAge = System.currentTimeMillis() - newLocation.getTime();
    }
    return locationAge;
}
 
Example 10
Source File: MainActivity.java    From LocationShare with GNU General Public License v3.0 5 votes vote down vote up
private boolean validLocation(Location location) {
    if (location == null) {
        return false;
    }

    // Location must be from less than 30 seconds ago to be considered valid
    if (Build.VERSION.SDK_INT < 17) {
        return System.currentTimeMillis() - location.getTime() < 30e3;
    } else {
        return SystemClock.elapsedRealtimeNanos() - location.getElapsedRealtimeNanos() < 30e9;
    }
}
 
Example 11
Source File: DeviceLocation.java    From ARCore-Location with MIT License 4 votes vote down vote up
private boolean filterAndAddLocation(Location location) {

        if (currentBestLocation == null) {
            currentBestLocation = location;

            locationEvents();
        }

        long age = getLocationAge(location);

        if (age > 5 * 1000) { //more than 5 seconds
            Log.d(TAG, "Location is old");
            oldLocationList.add(location);

            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: old", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (location.getAccuracy() <= 0) {
            Log.d(TAG, "Latitidue and longitude values are invalid.");
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: invalid", Toast.LENGTH_SHORT).show();
            noAccuracyLocationList.add(location);
            return false;
        }

        //setAccuracy(newLocation.getAccuracy());
        float horizontalAccuracy = location.getAccuracy();
        if (horizontalAccuracy > getMinimumAccuracy()) { //10meter filter
            Log.d(TAG, "Accuracy is too low.");
            inaccurateLocationList.add(location);
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: innacurate", Toast.LENGTH_SHORT).show();
            return false;
        }


        /* Kalman Filter */
        float Qvalue;

        long locationTimeInMillis = (long) (location.getElapsedRealtimeNanos() / 1000000);
        long elapsedTimeInMillis = locationTimeInMillis - runStartTimeInMillis;

        if (currentSpeed == 0.0f) {
            Qvalue = 3.0f; //3 meters per second
        } else {
            Qvalue = currentSpeed; // meters per second
        }

        kalmanFilter.Process(location.getLatitude(), location.getLongitude(), location.getAccuracy(), elapsedTimeInMillis, Qvalue);
        double predictedLat = kalmanFilter.get_lat();
        double predictedLng = kalmanFilter.get_lng();

        Location predictedLocation = new Location("");//provider name is unecessary
        predictedLocation.setLatitude(predictedLat);//your coords of course
        predictedLocation.setLongitude(predictedLng);
        float predictedDeltaInMeters = predictedLocation.distanceTo(location);

        if (predictedDeltaInMeters > 60) {
            Log.d(TAG, "Kalman Filter detects mal GPS, we should probably remove this from track");
            kalmanFilter.consecutiveRejectCount += 1;

            if (kalmanFilter.consecutiveRejectCount > 3) {
                kalmanFilter = new KalmanLatLong(3); //reset Kalman Filter if it rejects more than 3 times in raw.
            }

            kalmanNGLocationList.add(location);
            if (locationScene.isDebugEnabled())
                Toast.makeText(context, "Rejected: kalman filter", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            kalmanFilter.consecutiveRejectCount = 0;
        }


        Log.d(TAG, "Location quality is good enough.");
        currentBestLocation = predictedLocation;
        currentSpeed = location.getSpeed();
        locationList.add(location);

        locationEvents();


        return true;
    }
 
Example 12
Source File: GpsIconData.java    From Status with Apache License 2.0 4 votes vote down vote up
private long getElapsedTime(@NonNull Location location) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
        return location.getElapsedRealtimeNanos() - SystemClock.elapsedRealtimeNanos();
    else return location.getTime() - System.currentTimeMillis();
}
 
Example 13
Source File: LocationService.java    From AndroidLocationStarterKit with MIT License 4 votes vote down vote up
private boolean filterAndAddLocation(Location location){

        long age = getLocationAge(location);

        if(age > 5 * 1000){ //more than 5 seconds
            Log.d(TAG, "Location is old");
            oldLocationList.add(location);
            return false;
        }

        if(location.getAccuracy() <= 0){
            Log.d(TAG, "Latitidue and longitude values are invalid.");
            noAccuracyLocationList.add(location);
            return false;
        }

        //setAccuracy(newLocation.getAccuracy());
        float horizontalAccuracy = location.getAccuracy();
        if(horizontalAccuracy > 10){ //10meter filter
            Log.d(TAG, "Accuracy is too low.");
            inaccurateLocationList.add(location);
            return false;
        }


        /* Kalman Filter */
        float Qvalue;

        long locationTimeInMillis = (long)(location.getElapsedRealtimeNanos() / 1000000);
        long elapsedTimeInMillis = locationTimeInMillis - runStartTimeInMillis;

        if(currentSpeed == 0.0f){
            Qvalue = 3.0f; //3 meters per second
        }else{
            Qvalue = currentSpeed; // meters per second
        }

        kalmanFilter.Process(location.getLatitude(), location.getLongitude(), location.getAccuracy(), elapsedTimeInMillis, Qvalue);
        double predictedLat = kalmanFilter.get_lat();
        double predictedLng = kalmanFilter.get_lng();

        Location predictedLocation = new Location("");//provider name is unecessary
        predictedLocation.setLatitude(predictedLat);//your coords of course
        predictedLocation.setLongitude(predictedLng);
        float predictedDeltaInMeters =  predictedLocation.distanceTo(location);

        if(predictedDeltaInMeters > 60){
            Log.d(TAG, "Kalman Filter detects mal GPS, we should probably remove this from track");
            kalmanFilter.consecutiveRejectCount += 1;

            if(kalmanFilter.consecutiveRejectCount > 3){
                kalmanFilter = new KalmanLatLong(3); //reset Kalman Filter if it rejects more than 3 times in raw.
            }

            kalmanNGLocationList.add(location);
            return false;
        }else{
            kalmanFilter.consecutiveRejectCount = 0;
        }

        /* Notifiy predicted location to UI */
        Intent intent = new Intent("PredictLocation");
        intent.putExtra("location", predictedLocation);
        LocalBroadcastManager.getInstance(this.getApplication()).sendBroadcast(intent);

        Log.d(TAG, "Location quality is good enough.");
        currentSpeed = location.getSpeed();
        locationList.add(location);


        return true;
    }
 
Example 14
Source File: BackendHelper.java    From android_packages_apps_UnifiedNlp with Apache License 2.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void updateElapsedRealtimeNanos(Location location) {
    if (location.getElapsedRealtimeNanos() <= 0) {
        location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
}
 
Example 15
Source File: BetterWeatherExtension.java    From BetterWeather with Apache License 2.0 4 votes vote down vote up
/**
 * Requests a location update if setting is Automatic, else it will give a dummy location
 *
 * @param lm       Location Manager from {@link net.imatruck.betterweather.BetterWeatherExtension#onUpdateData(int)}
 * @param provider Provider determined in {@link net.imatruck.betterweather.BetterWeatherExtension#onUpdateData(int)}
 */
private void requestLocationUpdate(final LocationManager lm, final String provider) {
    if (provider != null && sUseCurrentLocation) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            handleMissingPermission();
            return;
        }
        final Location lastLocation = lm.getLastKnownLocation(provider);
        if (lastLocation == null ||
                (SystemClock.elapsedRealtimeNanos() - lastLocation.getElapsedRealtimeNanos())
                        >= STALE_LOCATION_NANOS) {
            LOGW(TAG, "Stale or missing last-known location; requesting single coarse location "
                    + "update. " + ((lastLocation != null) ? lastLocation.getLatitude() + ", " + lastLocation.getLongitude() : "Last location is null"));
            try {
                disableOneTimeLocationListener();
                mOneTimeLocationListenerActive = true;
                lm.requestSingleUpdate(provider, mOneTimeLocationListener, null);
                gpsFixHandler.postDelayed(new Runnable() {
                    public void run() {
                        disableOneTimeLocationListener();
                        LOGD(TAG, "We didn't get a GPS fix quick enough, we'll try again later");
                        scheduleRefresh(0);
                    }
                }, 30 * 1000);
                LOGD(TAG, "Requested single location update");
                if (lastLocation != null) {
                    new RefreshWeatherTask(lastLocation).execute();
                }
            } catch (Exception e) {
                LOGW(TAG, "RuntimeException on requestSingleUpdate. " + e.toString());
                scheduleRefresh(2);
            }
        } else {
            new RefreshWeatherTask(lastLocation).execute();
        }
    } else if (!sUseCurrentLocation) {
        LOGD(TAG, "Using set location");
        disableOneTimeLocationListener();
        Location dummyLocation = new Location(provider);
        new RefreshWeatherTask(dummyLocation).execute();
    } else {
        handleMissingPermission();
    }
}