1 /* 2 * Copyright 2022 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.google.android.libraries.mobiledatadownload.populator; 17 18 import android.Manifest.permission; 19 import android.content.Context; 20 import android.content.pm.PackageManager; 21 import android.location.Location; 22 import android.location.LocationManager; 23 import androidx.core.content.ContextCompat; 24 import com.google.common.base.Optional; 25 26 /** 27 * This common class defines a function that provides the device location to the Webref populator. 28 */ 29 final class LocationProviderImpl implements LocationProvider { 30 private final Context context; 31 private final LocationManager locationManager; 32 LocationProviderImpl(Context context, LocationManager locationManager)33 LocationProviderImpl(Context context, LocationManager locationManager) { 34 this.context = context; 35 this.locationManager = locationManager; 36 } 37 38 /** 39 * Returns the location according to network or GPS provider or returns absent if app doesn't have 40 * the permission to request the location. 41 */ 42 @Override get()43 public Optional<Location> get() { 44 if (ContextCompat.checkSelfPermission(context, permission.ACCESS_FINE_LOCATION) 45 == PackageManager.PERMISSION_DENIED 46 && ContextCompat.checkSelfPermission(context, permission.ACCESS_COARSE_LOCATION) 47 == PackageManager.PERMISSION_DENIED) { 48 return Optional.absent(); 49 } 50 51 Location networkProviderLocation = 52 locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 53 if (networkProviderLocation != null && networkProviderLocation.hasAccuracy()) { 54 return Optional.of(networkProviderLocation); 55 } 56 Location gpsProviderLocation = 57 locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 58 if (gpsProviderLocation != null && gpsProviderLocation.hasAccuracy()) { 59 return Optional.of(gpsProviderLocation); 60 } 61 return Optional.absent(); 62 } 63 } 64