下面列出了android.database.sqlite.SQLiteFullException#android.location.Location 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
/**
* Sends some locations which are moving and checks some simple policy.
*
* @param points number of locations
* @param startTime start time of this track
* @param tripStatistics the TripStatistics object
* @param timeOffset offset to start time
* @param locationOffset location offset to start
*/
private void addLocations(int points, long startTime, TripStatistics tripStatistics,
int timeOffset, int locationOffset) {
for (int i = 0; i < points; i++) {
// 99999 means a speed should bigger than given speed.
Location location = getLocation(i + locationOffset, (i + locationOffset) * .001, 99999,
startTime + (timeOffset + i) * TEN_SECONDS);
tripStatisticsUpdater.addLocation(location,
PreferencesUtils.RECORDING_DISTANCE_INTERVAL_DEFAULT, true, ActivityType.WALKING,
DEFAULT_WEIGHT);
tripStatistics = tripStatisticsUpdater.getTripStatistics();
assertTrue(tripStatistics.getMovingTime() <= tripStatistics.getTotalTime());
assertTrue(tripStatistics.getAverageSpeed() <= tripStatistics.getAverageMovingSpeed());
assertTrue(tripStatistics.getAverageMovingSpeed() <= tripStatistics.getMaxSpeed());
assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime());
}
}
public static String getDistance(AVGeoPoint p1, AVGeoPoint p2)
{
float[] results = new float[1];
Location.distanceBetween(p1.getLatitude(), p1.getLongitude(), p2.getLatitude(), p2
.getLongitude(), results);
int m = (int) results[0];
String strM = m + "";
if (strM.length() > 6)//换算成kkm
{
float kkm = m * 1.0f / (1000 * 1000);
kkm = Math.round(kkm * 100) * 1.0f / 10;
return kkm + "kkm";
} else if (strM.length() > 3)//换算成 km
{
float km = m * 1.0f / 1000;
km = Math.round(km * 100) * 1.0f / 10;
return km + "km";
}
return m + "m";
}
public Location getLocationInfo()
{
if (enableGeoLocation) {
if (locationManager == null)
{
// init location Manager
locationManager = new InfoGeoLocation(context);
locationManager.start();
}
final Location curLocation = locationManager.getLastKnownLocation();
if (curLocation != null && this.collectInformation)
{
geoLocations.add(new GeoLocationItem(curLocation.getTime(), curLocation.getLatitude(), curLocation
.getLongitude(), curLocation.getAccuracy(), curLocation.getAltitude(), curLocation.getBearing(),
curLocation.getSpeed(), curLocation.getProvider()));
Log.i(DEBUG_TAG, "Location: " + curLocation.toString());
}
return curLocation;
}
else {
return null;
}
}
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);
}
@Override
public void onLocationChanged( Location location )
{
Set<GeoFence> oldFences, newFences, currFence;
synchronized( this )
{
initFencesToCallback();
this.location = location;
oldFences = pointFences;
currFence = findGeoPointsFence( new GeoPoint( location.getLatitude(), location.getLongitude() ), fencesToCallback.keySet() );
newFences = new HashSet<GeoFence>( currFence );
newFences.removeAll( oldFences );
oldFences.removeAll( currFence );
callOnEnter( newFences );
callOnStay( newFences );
callOnExit( oldFences );
cancelOnStay( oldFences );
pointFences = currFence;
}
}
LocationTracker(Context context, LocationUSourceData data,
@NonNull PendingIntent event_positive,
@NonNull PendingIntent event_negative) {
super(context, data, event_positive, event_negative);
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
criteria = LocationUtils.getCriteria();
@SuppressLint("MissingPermission") Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (LocationUtils.isAcceptable(data, lastKnownLocation)) {
newSatisfiedState(LocationUtils.isInside(data, lastKnownLocation));
} else {
@SuppressLint("MissingPermission") Location lastKnownLocationGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (LocationUtils.isAcceptable(data, lastKnownLocationGps)) {
newSatisfiedState(LocationUtils.isInside(data, lastKnownLocationGps));
}
}
}
private void writeTrack(Location loc, boolean continous, boolean geoid, float smoothspeed, float avgspeed)
{
boolean needsWrite = false;
if (lastLocation != null)
{
distanceFromLastWriting += loc.distanceTo(lastLocation);
}
if (lastWritenLocation != null)
timeFromLastWriting = loc.getTime() - lastWritenLocation.getTime();
if (lastLocation == null || lastWritenLocation == null || !continous || timeFromLastWriting > maxTime || distanceFromLastWriting > minDistance && timeFromLastWriting > minTime)
{
needsWrite = true;
}
lastLocation = loc;
if (needsWrite)
writeLocation(loc, continous);
}
@Test
public void testGps_Satellites_NoFix() throws IOException {
// Set up fake device
LoopbackUartDevice gpsDevice = new LoopbackUartDevice();
NmeaGpsModule gpsModule = new NmeaGpsModule(gpsDevice, DEFAULT_BAUD, DEFAULT_ACCURACY, null);
GpsModuleCallback mockCallback = Mockito.mock(GpsModuleCallback.class);
gpsModule.setGpsModuleCallback(mockCallback);
// Inject NMEA test data
byte[] buffer = NmeaSampleData.SAMPLE_SAT_VIEW_NO_FIX;
gpsDevice.write(buffer, buffer.length);
// Verify callback results
Mockito.verify(mockCallback, times(6)).onNmeaMessage(anyString());
Mockito.verify(mockCallback, never()).onGpsTimeUpdate(anyLong());
Mockito.verify(mockCallback, never()).onGpsLocationUpdate(any(Location.class));
ArgumentCaptor<GnssStatus> args = ArgumentCaptor.forClass(GnssStatus.class);
Mockito.verify(mockCallback, times(1)).onGpsSatelliteStatus(args.capture());
GnssStatus status = args.getValue();
assertEquals(NmeaSampleData.EXPECTED_SAT_COUNT, status.getSatelliteCount());
}
protected RectF getMyLocationMapDrawingBounds(MapView mv, Location lastFix, RectF reuse) {
mv.getProjection().toMapPixels(mLatLng, mMapCoords);
reuse = getDrawingBounds(mMapCoords, lastFix, reuse);
// Add in the accuracy circle if enabled
if (mDrawAccuracyEnabled) {
final float radius = (float) Math.ceil(
lastFix.getAccuracy() / (float) Projection.groundResolution(
lastFix.getLatitude(), mMapView.getZoomLevel())
);
RectF accuracyRect =
new RectF(mMapCoords.x - radius, mMapCoords.y - radius, mMapCoords.x + radius,
mMapCoords.y + radius);
final float strokeWidth = (float) Math.ceil(
mCirclePaint.getStrokeWidth() == 0 ? 1 : mCirclePaint.getStrokeWidth());
accuracyRect.inset(-strokeWidth, -strokeWidth);
reuse.union(accuracyRect);
}
return reuse;
}
@Test
public void deleteLocationById() {
Context ctx = InstrumentationRegistry.getTargetContext();
SQLiteDatabase db = new SQLiteOpenHelper(ctx).getWritableDatabase();
SQLiteLocationDAO dao = new SQLiteLocationDAO(db);
BackgroundLocation bgLocation = new BackgroundLocation(new Location("fake"));
Collection<BackgroundLocation> locations = null;
Long locationId = dao.persistLocation(bgLocation);
locations = dao.getAllLocations();
Assert.assertEquals(1, locations.size());
dao.deleteLocationById(locationId);
locations = dao.getValidLocations();
Assert.assertEquals(0, locations.size());
}
/**
* Blurs the specified location with the defined blur radius or returns an unchanged location if no blur radius is set
*
* @param originalLocation the original location received from the device
* @return the blurred location
*/
private Location blurWithRadius(final Location originalLocation) {
if (mBlurRadius <= 0) {
return originalLocation;
}
else {
Location newLocation = new Location(originalLocation);
double blurMeterLong = calculateRandomOffset(mBlurRadius) / SQUARE_ROOT_TWO;
double blurMeterLat = calculateRandomOffset(mBlurRadius) / SQUARE_ROOT_TWO;
newLocation.setLongitude(newLocation.getLongitude() + meterToLongitude(blurMeterLong, newLocation.getLatitude()));
newLocation.setLatitude(newLocation.getLatitude() + meterToLatitude(blurMeterLat));
return newLocation;
}
}
public static double angle(double lat1, double long1, double lat2,
double long2) {
Location loc1 = new Location("network");
loc1.setLatitude(lat1);
loc1.setLongitude(long1);
Location loc2 = new Location("network");
loc2.setLatitude(lat2);
loc2.setLongitude(long2);
float brng = loc1.bearingTo(loc2);
float readyForEnglish = normalizeDegree(brng);
log("cbscience bearingTo " + brng + ", eng " + readyForEnglish + " " + englishDirection(readyForEnglish));
return readyForEnglish;
}
@Test
public void shouldNotDrawAnyPointsIfCancelled() throws Exception {
ArrayList<Location> locations = new ArrayList<Location>();
stub(box.contains(locationToGeoPoint(outsideBefore1))).toReturn(false);
stub(box.contains(locationToGeoPoint(outsideBefore2))).toReturn(false);
stub(box.contains(locationToGeoPoint(inside1))).toReturn(true);
stub(box.contains(locationToGeoPoint(inside2))).toReturn(true);
locations.add(outsideBefore1);
locations.add(outsideBefore2);
locations.add(inside1);
locations.add(inside2);
task.cancel(true);
task.execute(locations);
Robolectric.runUiThreadTasksIncludingDelayedTasks();
assertThat(getPathLayer()).isNull();
}
private void requestLocationUpdates() {
Set<String> mProviders = GeoUtils.evaluateProvidersWithPermissions(mLocationManager, context);
for (String provider : mProviders) {
// Ignore the inspector warnings; the permissions are already checked in evaluateProvidersWithPermissions.
if (location == null) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider);
if (lastKnownLocation != null) {
this.location = lastKnownLocation;
this.lastDisplayedLocation = lastKnownLocation;
Log.i("HereFunctionHandler", "last known location: " + this.location);
}
}
// Looper is necessary because requestLocationUpdates is called inside an AsyncTask (EntityLoaderTask).
// What values for minTime and minDistance?
mLocationManager.requestLocationUpdates(provider, 0, 0, this, Looper.getMainLooper());
requestingLocationUpdates = true;
}
}
@Test
public void centerMapOnLocation_shouldCallView() {
when(locationInteractor.isLocationAvailable()).thenReturn(Completable.complete());
Location location = mock(Location.class);
when(locationInteractor.getUpdatedLocation()).thenReturn(Single.just(location));
mapPresenter.centerMapOnLocation();
verify(view, times(1)).animateMapCamera(location);
}
@Test
public void onRecalculate_shouldAnnounceRecalculation() throws Exception {
initTestFragment();
TestHelper.startFragment(fragment, act);
Location testLocation = getTestLocation(111.0, 111.0);
fragment.onRecalculate(testLocation);
assertLastSpokenText(act.getString(R.string.recalculating));
}
private void fillStatusPanel(Location location){
if (mStatusPanelMode == 0)
return;
boolean needViewUpdate = true;
boolean isCurrentOrientationOneLine = mStatusPanel.getChildCount() > 0 &&
mStatusPanel.getChildAt(0).getId() == R.id.status_container_land;
View panel;
if (!isCurrentOrientationOneLine) {
panel = mActivity.getLayoutInflater().inflate(R.layout.status_panel_land, mStatusPanel, false);
defineTextViews(panel);
} else {
panel = mStatusPanel.getChildAt(0);
needViewUpdate = false;
}
fillTextViews(location);
if (!isFitOneLine()) {
panel = mActivity.getLayoutInflater().inflate(R.layout.status_panel, mStatusPanel, false);
defineTextViews(panel);
fillTextViews(location);
needViewUpdate = true;
}
if (needViewUpdate) {
mStatusPanel.removeAllViews();
panel.getBackground().setAlpha(128);
mStatusPanel.addView(panel);
}
}
/**
* Takes in a raw location, converts it to a point, and snaps it to the closest point along the
* route. This is isolated as separate logic from the snap logic provided because we will always
* need to snap to the route in order to get the most accurate information.
*/
static Point userSnappedToRoutePosition(Location location, List<Point> coordinates) {
if (coordinates.size() < 2) {
return Point.fromLngLat(location.getLongitude(), location.getLatitude());
}
Point locationToPoint = Point.fromLngLat(location.getLongitude(), location.getLatitude());
// Uses Turf's pointOnLine, which takes a Point and a LineString to calculate the closest
// Point on the LineString.
Feature feature = TurfMisc.nearestPointOnLine(locationToPoint, coordinates);
return ((Point) feature.geometry());
}
/**
* Gets a KML LineString value representing an array of locations.
*
* @param locations the locations.
* @return the KML LineString value.
*/
public static String getKmlLineString(ArrayList<Location> locations) {
StringBuilder builder = new StringBuilder("<LineString><coordinates>");
if (locations != null) {
for (int i = 0; i < locations.size(); i++) {
if (i != 0) {
builder.append(' ');
}
appendLocation(locations.get(i), builder);
}
}
builder.append("</coordinates></LineString>");
return builder.toString();
}
static boolean isInside(LocationUSourceData data, Location location) {
for (LatLong center : data.locations) {
if (inside(center, data.radius, location.getLatitude(), location.getLongitude())) {
return true;
}
}
return false;
}
@Override
public void onLocationChanged(@NonNull Location loc) {
mLocation = loc;
if ((mAdapter.getCount() <= 1)) {
autoLocation();
}
}
public Location getLastLocation() {
if (!connected.get()) {
updateLastLocation();
}
if (lastLocation == null) {
Log.d(TAG, "uh-ok: last location for " + name + " is null!");
}
return lastLocation;
}
public synchronized void scanGsm(final String calledFrom) {
if (thread != null) {
if (DEBUG)
Log.i(TAG, "scanGsm() : Thread busy?!");
return;
}
if (th != null) {
thread = new Thread(new Runnable() {
@Override
public void run() {
Location rslt = th.getLocationEstimate();
String logString;
if (rslt != null) {
rslt.setTime(System.currentTimeMillis());
logString = "scanGsm(" + calledFrom + ") " + rslt.toString();
} else
logString = "scanGsm(" + calledFrom + ") null position";
if (DEBUG)
Log.i(TAG, logString);
report(rslt);
thread = null;
}
});
thread.start();
} else if (DEBUG)
Log.i(TAG, "Telephony helper is null?!?");
}
@Override
public void onConnected(@Nullable Bundle bundle) {
// When we are connected to Google Play service
// Get last known recent location (maybe it's not very accurate)
Location lastLocation = locationService.getLastLocation();
// Note that this can be NULL if last location isn't already known
if (lastLocation != null) {
// Show last location
updateLocation(lastLocation);
}
// Begin polling for new location updates
locationService.createLocationRequest(this);
locationService.startLocationUpdates(this);
}
/**
* Returns an X-Geo HTTP header string if:
* 1. The current mode is not incognito.
* 2. The url is a google search URL (e.g. www.google.co.uk/search?q=cars), and
* 3. The user has not disabled sharing location with this url, and
* 4. There is a valid and recent location available.
*
* Returns null otherwise.
*
* @param context The Context used to get the device location.
* @param url The URL of the request with which this header will be sent.
* @param isIncognito Whether the request will happen in an incognito tab.
* @return The X-Geo header string or null.
*/
public static String getGeoHeader(Context context, String url, boolean isIncognito) {
if (!isGeoHeaderEnabledForUrl(context, url, isIncognito, true)) {
return null;
}
// Only send X-Geo header if there's a fresh location available.
Location location = GeolocationTracker.getLastKnownLocation(context);
if (location == null) {
recordHistogram(UMA_LOCATION_NOT_AVAILABLE);
return null;
}
if (GeolocationTracker.getLocationAge(location) > MAX_LOCATION_AGE) {
recordHistogram(UMA_LOCATION_STALE);
return null;
}
recordHistogram(UMA_HEADER_SENT);
// Timestamp in microseconds since the UNIX epoch.
long timestamp = location.getTime() * 1000;
// Latitude times 1e7.
int latitude = (int) (location.getLatitude() * 10000000);
// Longitude times 1e7.
int longitude = (int) (location.getLongitude() * 10000000);
// Radius of 68% accuracy in mm.
int radius = (int) (location.getAccuracy() * 1000);
// Encode location using ascii protobuf format followed by base64 encoding.
// https://goto.google.com/partner_location_proto
String locationAscii = String.format(Locale.US,
"role:1 producer:12 timestamp:%d latlng{latitude_e7:%d longitude_e7:%d} radius:%d",
timestamp, latitude, longitude, radius);
String locationBase64 = new String(Base64.encode(locationAscii.getBytes(), Base64.NO_WRAP));
return "X-Geo: a " + locationBase64;
}
@Deprecated
@org.xwalk.core.JavascriptInterface
@android.webkit.JavascriptInterface
@SuppressLint("MissingPermission") // handled by catch(Exception)
/**
* @deprecated Location should be fetched directly from the browser.
* @see https://github.com/medic/medic-webapp/issues/3781
*/
public String getLocation() {
try {
if(locationManager == null) return jsonError("LocationManager not set. Cannot retrieve location.");
String provider = locationManager.getBestProvider(new Criteria(), true);
if(provider == null) return jsonError("No location provider available.");
Location loc = locationManager.getLastKnownLocation(provider);
if(loc == null) return jsonError("Provider '" + provider + "' did not provide a location.");
return new JSONObject()
.put("lat", loc.getLatitude())
.put("long", loc.getLongitude())
.toString();
} catch(Exception ex) {
return jsonError("Problem fetching location: ", ex);
}
}
@Override
public void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
if (location != null) {
updateTextView(location);
}
}
private boolean isBetterLocation(Location prev, Location current) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean pref_altitude = prefs.getBoolean(SettingsFragment.PREF_ALTITUDE, SettingsFragment.DEFAULT_ALTITUDE);
return (prev == null ||
((!pref_altitude || !prev.hasAltitude() || current.hasAltitude()) &&
(current.hasAccuracy() ? current.getAccuracy() : Float.MAX_VALUE) <
(prev.hasAccuracy() ? prev.getAccuracy() : Float.MAX_VALUE)));
}
private void onLocationUnavailable() {
if (foundContextBot != null && foundContextBot.bot_inline_geo) {
lastKnownLocation = new Location("network");
lastKnownLocation.setLatitude(-1000);
lastKnownLocation.setLongitude(-1000);
searchForContextBotResults(true, foundContextBot, searchingContextQuery, "");
}
}