Java Code Examples for android.location.LocationManager#requestLocationUpdates()

The following examples show how to use android.location.LocationManager#requestLocationUpdates() . 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: LocationHelper.java    From RxAndroidBootstrap with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize starting values and starting best location listeners
 *
 * @param ctx
 * @param result
 */
public void init(Context ctx, LocationResult result) {
    context = ctx;
    locationResult = result;

    myLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    gps_enabled = (Boolean) myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    bestLocation = null;
    counts = 0;

    // turning on location updates
    myLocationManager.requestLocationUpdates("network", 0, 0, networkLocationListener);
    myLocationManager.requestLocationUpdates("gps", 0, 0, gpsLocationListener);
    myLocationManager.addGpsStatusListener(gpsStatusListener);

    // starting best location finder loop
    handler.postDelayed(showTime, iteration_timeout_step);
}
 
Example 2
Source File: BoundLocationManager.java    From android-lifecycles with Apache License 2.0 6 votes vote down vote up
void addLocationListener() {
    // Note: Use the Fused Location Provider from Google Play Services instead.
    // https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi

    mLocationManager =
            (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mListener);
    Log.d("BoundLocationMgr", "Listener added");

    // Force an update with the last location, if available.
    Location lastLocation = mLocationManager.getLastKnownLocation(
            LocationManager.GPS_PROVIDER);
    if (lastLocation != null) {
        mListener.onLocationChanged(lastLocation);
    }
}
 
Example 3
Source File: QuizActivity.java    From CoolSignIn with Apache License 2.0 6 votes vote down vote up
private void getLocation() {
    locationManager = (LocationManager) MyApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyApplication.getContext(),
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(QuizActivity.this, "我没有位置权限 ( > c < ) ", Toast.LENGTH_SHORT).show();
        String locationPermissions[] = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= 23) {
            requestPermissions(locationPermissions, REQUEST_CODE_FOR_POSITON);
        }
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
}
 
Example 4
Source File: SampleCustomMyLocation.java    From osmdroid with Apache License 2.0 6 votes vote down vote up
public void onResume() {
    super.onResume();
    mgr = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    try {
        mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, this);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 5
Source File: BaseActivity.java    From JsBridge with Apache License 2.0 6 votes vote down vote up
public Location getLocation(LocationListener listener) {
    locationListener = listener;
    mLocationManager = (LocationManager) HiApplication.getInstance().getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    String locationProvider = null;
    if (providers.contains(LocationManager.GPS_PROVIDER)) {
        //如果是GPS
        locationProvider = LocationManager.GPS_PROVIDER;
    } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
        //如果是Network
        locationProvider = LocationManager.NETWORK_PROVIDER;
    }
    Location location = mLocationManager.getLastKnownLocation(locationProvider);
    mLocationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
    return location;
}
 
Example 6
Source File: RxLocationTool.java    From RxTools-master with Apache License 2.0 6 votes vote down vote up
/**
 * 注册
 * <p>使用完记得调用{@link #unRegisterLocation()}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>}</p>
 * <p>如果{@code minDistance}为0,则通过{@code minTime}来定时更新;</p>
 * <p>{@code minDistance}不为0,则以{@code minDistance}为准;</p>
 * <p>两者都为0,则随时刷新。</p>
 *
 * @param minTime     位置信息更新周期(单位:毫秒)
 * @param minDistance 位置变化最小距离:当位置距离变化超过此值时,将更新位置信息(单位:米)
 * @param listener    位置刷新的回调接口
 * @return {@code true}: 初始化成功<br>{@code false}: 初始化失败
 */
public static boolean registerLocation(Context context, long minTime, long minDistance, OnLocationChangeListener listener) {
    if (listener == null) return false;
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        return false;
    }
    mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    mListener = listener;
    if (!isLocationEnabled(context)) {
        RxToast.showToast(context, "无法定位,请打开定位服务", 500);
        return false;
    }
    String provider = mLocationManager.getBestProvider(getCriteria(), true);

    Location location = mLocationManager.getLastKnownLocation(provider);
    if (location != null) listener.getLastKnownLocation(location);
    if (myLocationListener == null) myLocationListener = new MyLocationListener();
    mLocationManager.requestLocationUpdates(provider, minTime, minDistance, myLocationListener);
    return true;
}
 
Example 7
Source File: ActivityEditTransaction.java    From fingen with Apache License 2.0 6 votes vote down vote up
@NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
void startDetectCoords() {
    if (transaction.getLocationID() < 0 & allowUpdateLocation) {
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager != null && locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
            }

        if (locationManager != null && locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
    }
}
 
Example 8
Source File: MeasurementService.java    From NoiseCapture with GNU General Public License v3.0 5 votes vote down vote up
private void initPassive() {
    if (passiveLocationListener == null) {
        passiveLocationListener = new CommonLocationListener(this, LISTENER.PASSIVE);
    }
    passiveLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
            PackageManager.PERMISSION_GRANTED
            && passiveLocationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
        passiveLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
                minTimeDelay, 0, passiveLocationListener);
    }
}
 
Example 9
Source File: DeviceLocation.java    From ARCore-Location with MIT License 5 votes vote down vote up
public DeviceLocation() {

        try {
            // Getting LocationManager object
            locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
            // Creating an empty criteria object
            Criteria criteria = new Criteria();

            // Getting the name of the provider that meets the criteria
            provider = locationManager.getBestProvider(criteria, false);

            if (provider != null && !provider.equals("")) {

                // Get the location from the given provider
                Location location = locationManager.getLastKnownLocation(provider);
                locationManager.requestLocationUpdates(provider, 1000, 1, this);

                if (location != null)
                    onLocationChanged(location);
                else
                    Toast.makeText(activity, "Location can't be retrieved", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(activity, "No Provider Found", Toast.LENGTH_SHORT).show();
            }

        } catch (SecurityException e) {
            Toast.makeText(activity, "Enable location permissions from settings", Toast.LENGTH_SHORT).show();
        }
    }
 
Example 10
Source File: DiagnosticsActivity.java    From osmdroid with Apache License 2.0 5 votes vote down vote up
public void onResume() {
    super.onResume();
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    try {
        lm.addGpsStatusListener(this);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    } catch (SecurityException e) {
    } catch (RuntimeException r) {
    }
}
 
Example 11
Source File: MainFragment.java    From prayer-times-android with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (mRefresh == item) {
        mOnlyNew = true;
        if (PermissionUtils.get(getActivity()).pLocation) {
            LocationManager locMan = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

            locMan.removeUpdates(this);
            List<String> providers = locMan.getProviders(true);
            for (String provider : providers) {
                locMan.requestLocationUpdates(provider, 0, 0, this);
            }
        }
    } else if (mSwitch == item) {
        Preferences.SHOW_COMPASS_NOTE.set(false);
        // compass >> time >> map
        if (mMode == Mode.Map) {
            updateFrag(Mode.Compass);
            mSwitch.setIcon(MaterialDrawableBuilder.with(getActivity()).setIcon(MaterialDrawableBuilder.IconValue.CLOCK).setColor(Color.WHITE)
                    .setToActionbarSize().build());
        } else if (mMode == Mode.Compass) {
            updateFrag(Mode.Time);
            mSwitch.setIcon(MaterialDrawableBuilder.with(getActivity()).setIcon(MaterialDrawableBuilder.IconValue.MAP).setColor(Color.WHITE)
                    .setToActionbarSize().build());
        } else if (mMode == Mode.Time) {
            updateFrag(Mode.Map);
            mSwitch.setIcon(
                    MaterialDrawableBuilder.with(getActivity()).setIcon(MaterialDrawableBuilder.IconValue.COMPASS_OUTLINE).setColor(Color.WHITE)
                            .setToActionbarSize().build());
        } else {
            Toast.makeText(getActivity(), R.string.permissionNotGranted, Toast.LENGTH_LONG).show();
        }
    }

    return super.onOptionsItemSelected(item);
}
 
Example 12
Source File: PeriodicPositionUploaderTask.java    From secureit with MIT License 5 votes vote down vote up
/**
 * Constructor
 * @param context
 * @param lat
 * @param lng
 */
public PeriodicPositionUploaderTask(Context context) {
	this.context = context;
	locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
	
	if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
	if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
	
	prefs = new SecureItPreferences(context);
		
	this.phoneId = prefs.getPhoneId();
	this.accessToken = prefs.getAccessToken();
}
 
Example 13
Source File: Positioning.java    From experimental-fall-detector-android-app with MIT License 5 votes vote down vote up
private void reset() {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    manager.removeUpdates(this);
    int meters10 = 10;
    int minutes10 = 10 * 60 * 1000;
    manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minutes10, meters10, this);
}
 
Example 14
Source File: SensorNotificationService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void onBootPhase(int phase) {
    if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
        mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
        mMetaSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_DYNAMIC_SENSOR_META);
        if (mMetaSensor == null) {
            if (DBG) Slog.d(TAG, "Cannot obtain dynamic meta sensor, not supported.");
        } else {
            mSensorManager.registerListener(this, mMetaSensor,
                    SensorManager.SENSOR_DELAY_FASTEST);
        }
    }

    if (phase == PHASE_BOOT_COMPLETED) {
        // LocationManagerService is initialized after PHASE_THIRD_PARTY_APPS_CAN_START
        mLocationManager =
                (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        if (mLocationManager == null) {
            if (DBG) Slog.d(TAG, "Cannot obtain location service.");
        } else {
            mLocationManager.requestLocationUpdates(
                    LocationManager.PASSIVE_PROVIDER,
                    LOCATION_MIN_TIME,
                    LOCATION_MIN_DISTANCE,
                    this);
        }
    }
}
 
Example 15
Source File: LocationReceiver.java    From prayer-times-android with Apache License 2.0 5 votes vote down vote up
public static void start(Context c) {
    if (!hasPermission(c) || !useAutoLocation())
        return;

    LocationManager lm = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
    lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 1000 * 60 * 30, 5000, getPendingIntent(c));
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60 * 30, 5000, getPendingIntent(c));
}
 
Example 16
Source File: Positioning.java    From experimental-fall-detector-android-app with MIT License 5 votes vote down vote up
private void run() {
    enforce(context);
    synchronized (lock) {
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        once = System.currentTimeMillis();
        replied = false;
    }
}
 
Example 17
Source File: WeathForceActivity.java    From osmdroid with Apache License 2.0 4 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();

    //lock the device in current screen orientation
    int orientation;
    int rotation = ((WindowManager) this.getSystemService(
            Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
    switch (rotation) {
        case Surface.ROTATION_0:
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            this.deviceOrientation = 0;
            break;
        case Surface.ROTATION_90:
            this.deviceOrientation = 90;
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            break;
        case Surface.ROTATION_180:
            this.deviceOrientation = 180;
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            break;
        default:
            this.deviceOrientation = 270;
            orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            break;
    }

    this.setRequestedOrientation(orientation);


    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    try {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    } catch (Exception ex) {
    }
    compass = new InternalCompassOrientationProvider(this);
    compass.startOrientationProvider(this);
    mMapView.getController().zoomTo(14);

}
 
Example 18
Source File: LocationUtils.java    From XPermissionUtils with Apache License 2.0 4 votes vote down vote up
private static void startLocation(Context context) {
    //获取地理位置管理器
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    //获取所有可用的位置提供器
    List<String> providers = locationManager.getProviders(true);
    if (providers == null) {
        return;
    }

    //获取Location
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    //对提供者进行排序,gps、net、passive
    List<String> providerSortList = new ArrayList<>();
    if (providers.contains(LocationManager.GPS_PROVIDER)) {
        Log.d(TAG, "GPS_PROVIDER");
        providerSortList.add(LocationManager.GPS_PROVIDER);
    }
    if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
        Log.d(TAG, "NETWORK_PROVIDER");
        providerSortList.add(LocationManager.NETWORK_PROVIDER);
    }
    if (providers.contains(LocationManager.PASSIVE_PROVIDER)) {
        Log.d(TAG, "PASSIVE_PROVIDER");
        providerSortList.add(LocationManager.PASSIVE_PROVIDER);
    }
    String locationProvider = "";
    for (int i = 0; i < providerSortList.size(); i++) {
        String provider = providerSortList.get(i);
        Log.d(TAG, "正在尝试:" + provider);
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            locationProvider = provider;
            Log.d(TAG, "定位成功:" + provider);
            saveLocation(location);
            break;
        } else {
            Log.d(TAG, "定位失败:" + provider);
        }
    }
    if (!TextUtils.isEmpty(locationProvider)) {
        locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
    }
}
 
Example 19
Source File: GPSTracker.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
public void detectLocation() {
    try {
        locationManager = (LocationManager) G.context.getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            Log.i("GPS", "no network provider is enabled");
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // if GPS Enabled get lat/long using GPS Services

            if (isNetworkEnabled) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                }
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        if (G.onLocationChanged != null) {
                            G.onLocationChanged.onLocationChanged(location);
                        }
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            if (G.onLocationChanged != null) {
                                G.onLocationChanged.onLocationChanged(location);
                            }
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 20
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void handleRequestLocation(boolean independentFromGnss) {
    if (isRequestLocationRateLimited()) {
        if (DEBUG) {
            Log.d(TAG, "RequestLocation is denied due to too frequent requests.");
        }
        return;
    }
    ContentResolver resolver = mContext.getContentResolver();
    long durationMillis = Settings.Global.getLong(
            resolver,
            Settings.Global.GNSS_HAL_LOCATION_REQUEST_DURATION_MILLIS,
            LOCATION_UPDATE_DURATION_MILLIS);
    if (durationMillis == 0) {
        Log.i(TAG, "GNSS HAL location request is disabled by Settings.");
        return;
    }

    LocationManager locationManager = (LocationManager) mContext.getSystemService(
            Context.LOCATION_SERVICE);
    String provider;
    LocationChangeListener locationListener;

    if (independentFromGnss) {
        // For fast GNSS TTFF
        provider = LocationManager.NETWORK_PROVIDER;
        locationListener = mNetworkLocationListener;
    } else {
        // For Device-Based Hybrid (E911)
        provider = LocationManager.FUSED_PROVIDER;
        locationListener = mFusedLocationListener;
    }

    Log.i(TAG,
            String.format(
                    "GNSS HAL Requesting location updates from %s provider for %d millis.",
                    provider, durationMillis));
    try {
        locationManager.requestLocationUpdates(provider,
                LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS, /*minDistance=*/ 0,
                locationListener, mHandler.getLooper());
        locationListener.numLocationUpdateRequest++;
        mHandler.postDelayed(() -> {
            if (--locationListener.numLocationUpdateRequest == 0) {
                Log.i(TAG,
                        String.format("Removing location updates from %s provider.", provider));
                locationManager.removeUpdates(locationListener);
            }
        }, durationMillis);
    } catch (IllegalArgumentException e) {
        Log.w(TAG, "Unable to request location.", e);
    }
}