/* * Returns the last known location of the device using its GPS and network location providers. * May be null if: * - Location permissions are not requested in the Android manifest file * - The location providers don't exist * - Location awareness is disabled in the parent MoPubView */ private Location getLastKnownLocation() { LocationAwareness locationAwareness = mMoPubView.getLocationAwareness(); int locationPrecision = mMoPubView.getLocationPrecision(); Location result = null; if (locationAwareness == LocationAwareness.LOCATION_AWARENESS_DISABLED) { return null; } LocationManager lm = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE); Location gpsLocation = null; try { gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); } catch (SecurityException e) { Log.d("MoPub", "Failed to retrieve GPS location: access appears to be disabled."); } catch (IllegalArgumentException e) { Log.d("MoPub", "Failed to retrieve GPS location: device has no GPS provider."); } Location networkLocation = null; try { networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } catch (SecurityException e) { Log.d("MoPub", "Failed to retrieve network location: access appears to be disabled."); } catch (IllegalArgumentException e) { Log.d("MoPub", "Failed to retrieve network location: device has no network provider."); } if (gpsLocation == null && networkLocation == null) { return null; } else if (gpsLocation != null && networkLocation != null) { if (gpsLocation.getTime() > networkLocation.getTime()) result = gpsLocation; else result = networkLocation; } else if (gpsLocation != null) result = gpsLocation; else result = networkLocation; // Truncate latitude/longitude to the number of digits specified by locationPrecision. if (locationAwareness == LocationAwareness.LOCATION_AWARENESS_TRUNCATED) { double lat = result.getLatitude(); double truncatedLat = BigDecimal.valueOf(lat) .setScale(locationPrecision, BigDecimal.ROUND_HALF_DOWN) .doubleValue(); result.setLatitude(truncatedLat); double lon = result.getLongitude(); double truncatedLon = BigDecimal.valueOf(lon) .setScale(locationPrecision, BigDecimal.ROUND_HALF_DOWN) .doubleValue(); result.setLongitude(truncatedLon); } return result; }