android.location.LocationManager Java Examples

The following examples show how to use android.location.LocationManager. 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: LocationManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all providers by name, including passive and the ones that are not permitted to
 * be accessed by the calling activity or are currently disabled, but excluding fused.
 */
@Override
public List<String> getAllProviders() {
    ArrayList<String> out;
    synchronized (mLock) {
        out = new ArrayList<>(mProviders.size());
        for (LocationProviderInterface provider : mProviders) {
            String name = provider.getName();
            if (LocationManager.FUSED_PROVIDER.equals(name)) {
                continue;
            }
            out.add(name);
        }
    }
    if (D) Log.d(TAG, "getAllProviders()=" + out);
    return out;
}
 
Example #2
Source File: GeoPointActivity.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setTitle(StringUtils.getStringRobust(this, R.string.application_name) +
            " > " + StringUtils.getStringRobust(this, R.string.get_location));

    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    providers = GeoUtils.evaluateProviders(locationManager);

    setupLocationDialog();
    long mLong = -1;
    if (savedInstanceState != null) {
        mLong = savedInstanceState.getLong("millisRemaining", -1);
    }
    if (mLong > 0) {
        mTimer = new TimeoutTimer(mLong, this);
    } else {
        mTimer = new TimeoutTimer(HiddenPreferences.getGpsWidgetTimeoutInMilliseconds(), this);
    }
    mTimer.start();
}
 
Example #3
Source File: MapLocationUtil.java    From lunzi with Apache License 2.0 6 votes vote down vote up
private String getProvider(LocationManager locationManager) {
    // 构建位置查询条件
    Criteria criteria = new Criteria();
    // 查询精度:高
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // 速度
    criteria.setSpeedRequired(false);
    // 是否查询海拨:否
    criteria.setAltitudeRequired(false);
    // 是否查询方位角:否
    criteria.setBearingRequired(false);
    // 电量要求:低
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    // 返回最合适的符合条件的provider,第2个参数为true说明,如果只有一个provider是有效的,则返回当前provider
    return locationManager.getBestProvider(criteria, true);
}
 
Example #4
Source File: AppLocationFragment.java    From GooglePlayServiceLocationSupport with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiAvailability = GoogleApiAvailability.getInstance();
    mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).
            addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();

    mLocationService = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

    mLocationRequest = LocationRequest.create();

    Bundle bundle = getArguments();
    if (bundle != null)
        enableUpdates = bundle.getBoolean(AppLocation.REQUEST_UPDATES, true);
    else
        enableUpdates = true;

}
 
Example #5
Source File: LocationProvider.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean usePassiveOneShotLocation() {
    if (!isOnlyPassiveLocationProviderEnabled()) return false;

    // Do not request a location update if the only available location provider is
    // the passive one. Make use of the last known location and call
    // onLocationChanged directly.
    final Location location = mLocationManager.getLastKnownLocation(
            LocationManager.PASSIVE_PROVIDER);
    if (location != null) {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateNewLocation(location);
            }
        });
    }
    return true;
}
 
Example #6
Source File: LooperThread.java    From PocketMaps with MIT License 6 votes vote down vote up
/**
 *
 * @param context
 * @param useProvider
 * @param minTimeFilter
 * @param minTimeGpsProvider
 * @param minTimeNetProvider
 * @param locationListener
 * @param forwardProviderUpdates
 */
LooperThread(
        Context context,
        UseProvider useProvider,
        long minTimeFilter,
        long minTimeGpsProvider,
        long minTimeNetProvider,
        LocationListener locationListener,
        boolean forwardProviderUpdates)
{
    mContext = context;
    mClientHandler = new Handler();
    mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

    mUseProvider = useProvider;

    mMinTimeFilter = minTimeFilter;
    mMinTimeGpsProvider = minTimeGpsProvider;
    mMinTimeNetProvider = minTimeNetProvider;

    mClientLocationListener = locationListener;
    mForwardProviderUpdates = forwardProviderUpdates;

    start();
}
 
Example #7
Source File: DeviceLocation.java    From kickflip-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Get the last known location.
 * If one is not available, fetch
 * a fresh location
 *
 * @param context
 * @param waitForGpsFix
 * @param cb
 */
public static void getLastKnownLocation(Context context, boolean waitForGpsFix, final LocationResult cb) {
    DeviceLocation deviceLocation = new DeviceLocation();

    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location last_loc;
    last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (last_loc == null)
        last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    if (last_loc != null && cb != null) {
        cb.gotLocation(last_loc);
    } else {
        deviceLocation.getLocation(context, cb, waitForGpsFix);
    }
}
 
Example #8
Source File: ActivityEditLocation2.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 (location.getID() < 0) {
        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 #9
Source File: MainActivity.java    From good-weather with GNU General Public License v3.0 6 votes vote down vote up
public void gpsRequestLocation() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Looper locationLooper = Looper.myLooper();
        locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mLocationListener, locationLooper);
        final Handler locationHandler = new Handler(locationLooper);
        locationHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                locationManager.removeUpdates(mLocationListener);
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (lastLocation != null) {
                        mLocationListener.onLocationChanged(lastLocation);
                    } else {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
                    }
                }
            }
        }, LOCATION_TIMEOUT_IN_MS);
    }
}
 
Example #10
Source File: PermissionUtil.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
/**
 * 检测是否有定位权限,不可靠,比如在室内打开app,这种情况下定位模块没有值,会报无权限
 *
 * @return
 */
@SuppressLint("MissingPermission")
public static boolean checkLocationUnreliable(Context context) {
    try {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Location location2 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        return location != null || location2 != null;
    } catch (Exception e) {
        return false;
    }
}
 
Example #11
Source File: ShellLocationModeSetting.java    From test-butler with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
int getLocationMode() {
    String locationProviders = getLocationProviders();
    boolean gps = isProviderEnabled(locationProviders, LocationManager.GPS_PROVIDER);
    boolean network = isProviderEnabled(locationProviders, LocationManager.NETWORK_PROVIDER);

    if (gps && network) {
        return Settings.Secure.LOCATION_MODE_HIGH_ACCURACY;
    } else if (gps) {
        return Settings.Secure.LOCATION_MODE_SENSORS_ONLY;
    } else if (network) {
        return Settings.Secure.LOCATION_MODE_BATTERY_SAVING;
    } else {
        return Settings.Secure.LOCATION_MODE_OFF;
    }
}
 
Example #12
Source File: LocationSubjectTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Test
public void isAt_notAt() {
  Location location = new Location(LocationManager.GPS_PROVIDER);
  location.setLatitude(1);
  location.setLongitude(-1);

  Location other = new Location(LocationManager.GPS_PROVIDER);
  other.setLatitude(1);
  other.setLongitude(-2);

  try {
    assertThat(location).isAt(other);
    fail();
  } catch (AssertionError e) {
    assertThat(e).factValue("expected").isEqualTo("-2.0");
    assertThat(e).factValue("but was").isEqualTo("-1.0");
  }
}
 
Example #13
Source File: LocationLogic.java    From redalert-android with Apache License 2.0 6 votes vote down vote up
public static Location GetLastKnownLocation(Context context) {
    // Get location manager
    LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

    // Create location criteria
    Criteria criteria = new Criteria();

    // Set fine accuracy
    criteria.setAccuracy(criteria.ACCURACY_FINE);

    // Get best provider
    String bestProvider = locationManager.getBestProvider(criteria, false);

    // No provider?
    if (bestProvider == null) {
        // Return null
        return null;
    }

    // Return last location
    return locationManager.getLastKnownLocation(bestProvider);
}
 
Example #14
Source File: GpsConnection.java    From WhereYouGo with GNU General Public License v3.0 6 votes vote down vote up
private synchronized void handleOnLocationChanged(Location location) {
    // Logger.d(TAG, "handleOnLocationChanged(), fix:" + isFixed + ", loc:" + location);
    if (!isFixed) {
        if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
            if (Preferences.GPS_BEEP_ON_GPS_FIX)
                UtilsAudio.playBeep(1);
            disableNetwork();
            isFixed = true;
        }
        LocationState.onLocationChanged(location);
    } else {
        if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
            LocationState.onLocationChanged(location);
            setNewTimer();
        } else {
            // do not send location
        }
    }
}
 
Example #15
Source File: LocationHelper.java    From MVPAndroidBootstrap with Apache License 2.0 6 votes vote down vote up
public static Location getLastKnownLocation(Context context) {
    LocationManager mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}
 
Example #16
Source File: BacKService.java    From kute with Apache License 2.0 6 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    resultReceiver = intent.getParcelableExtra("receiver");
    this.m_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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.

    }
    this.m_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 5, this);
    this.m_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 5, this);

    return START_STICKY;
}
 
Example #17
Source File: GeolocationTracker.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Requests an updated location if the last known location is older than maxAge milliseconds.
 *
 * Note: this must be called only on the UI thread.
 */
@SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC")
static void refreshLastKnownLocation(Context context, long maxAge) {
    ThreadUtils.assertOnUiThread();

    // We're still waiting for a location update.
    if (sListener != null) return;

    LocationManager locationManager =
            (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location == null || getLocationAge(location) > maxAge) {
        String provider = LocationManager.NETWORK_PROVIDER;
        if (locationManager.isProviderEnabled(provider)) {
            sListener = new SelfCancelingListener(locationManager);
            locationManager.requestSingleUpdate(provider, sListener, null);
        }
    }
}
 
Example #18
Source File: LocationState.java    From WhereYouGo with GNU General Public License v3.0 6 votes vote down vote up
static void onStatusChanged(String provider, int status, Bundle extras) {
    Logger.w(TAG, "onStatusChanged(" + provider + ", " + status + ", " + extras + ")");
    for (int i = 0; i < mListeners.size(); i++) {
        mListeners.get(i).onStatusChanged(provider, status, extras);
    }

    // status 1 - provider disabled
    // status 2 - provider enabled
    // if GPS provider is disabled, set location only as network
    if (provider.equals(LocationManager.GPS_PROVIDER) && status == 1) {
        if (LocationState.location != null) {
            LocationState.location.setProvider(LocationManager.NETWORK_PROVIDER);
            onLocationChanged(LocationState.location);
        }
    }
    // uncomment if GPS must be enabled
    // if (provider.equals(LocationManager.GPS_PROVIDER) && status == 1) {
    // setGpsOff(null);
    // }
}
 
Example #19
Source File: GuidingActivity.java    From WhereYouGo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onOrientationChanged(float azimuth, float pitch, float roll) {
    // Logger.d(TAG, "onOrientationChanged(" + azimuth + ", " + pitch + ", " + roll + ")");
    Location loc = LocationState.getLocation();
    mAzimuth = azimuth;
    mPitch = pitch;
    mRoll = roll;

    String provider = loc.getProvider();
    switch (provider) {
        case LocationManager.GPS_PROVIDER:
            provider = getString(R.string.provider_gps);
            break;
        case LocationManager.NETWORK_PROVIDER:
            provider = getString(R.string.provider_network);
            break;
        default:
            provider = getString(R.string.provider_passive);
            break;
    }
    viewProvider.setText(provider);
    viewLat.setText(UtilsFormat.formatLatitude(loc.getLatitude()));
    viewLon.setText(UtilsFormat.formatLongitude(loc.getLongitude()));
    viewAlt.setText(UtilsFormat.formatAltitude(loc.getAltitude(), true));
    viewAcc.setText(UtilsFormat.formatDistance((double) loc.getAccuracy(), false));
    viewSpeed.setText(UtilsFormat.formatSpeed(loc.getSpeed(), false));

    repaint();
}
 
Example #20
Source File: a.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
a(Context context, LocationManager locationmanager)
{
    i = null;
    j = null;
    k = new Vector();
    a = null;
    b = null;
    c = false;
    e = true;
    f = true;
    o = 2000L;
    p = 10F;
    h = context;
    c();
    if (Looper.myLooper() == null)
    {
        j = new com.amap.api.location.j(this, context.getMainLooper());
    } else
    {
        j = new com.amap.api.location.j(this);
    }
    a = new com.amap.api.location.d(context, locationmanager, j, this);
    b = new c(context, j, this);
    b(false);
    e = true;
    f = true;
    g = new b(this, context);
}
 
Example #21
Source File: Util.java    From androidnative.pri with Apache License 2.0 5 votes vote down vote up
static void getGPSStatus() {
      Activity activity = org.qtproject.qt5.android.QtNative.activity();
      LocationManager manager = (LocationManager) activity.getSystemService( activity.LOCATION_SERVICE );
      boolean gpsstatus = manager.isProviderEnabled( LocationManager.GPS_PROVIDER );
      Map reply = new HashMap();
      reply.put("gpsstatus", gpsstatus );
      SystemDispatcher.dispatch(GOT_GPS_STATUS_MSG,reply);
}
 
Example #22
Source File: LocationHelper.java    From PrayTime-Android with Apache License 2.0 5 votes vote down vote up
public void removePassiveLocationUpdates(Context context, PendingIntent pendingIntent) {
  LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
  try {
    locationManager.removeUpdates(pendingIntent);
  } catch (SecurityException se) {
    //do nothing. We should always have permision in order to reach this screen.
  }
}
 
Example #23
Source File: CapturePosition.java    From itracing2 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent)
{
    // because some customers don't like Google Play Services…
    Location bestLocation = null;
    final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    for (final String provider : locationManager.getAllProviders()) {
        final Location location = locationManager.getLastKnownLocation(provider);
        final long now = System.currentTimeMillis();
        if (location != null
                && (bestLocation == null || location.getTime() > bestLocation.getTime())
                && location.getTime() > now - MAX_AGE) {
            bestLocation = location;
        }
    }

    if (bestLocation == null) {
        final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        locationManager.requestSingleUpdate(criteria, pendingIntent);
    }

    if (bestLocation != null) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        final String position = bestLocation.getLatitude() + "," + bestLocation.getLongitude();
        final Intent mapIntent = getMapIntent(position);

        final Notification notification = new Notification.Builder(context)
                .setContentText(context.getString(R.string.display_last_position))
                .setContentTitle(context.getString(R.string.app_name))
                .setSmallIcon(R.drawable.ic_launcher)
                .setAutoCancel(false)
                .setContentIntent(PendingIntent.getActivity(context, 0, mapIntent, PendingIntent.FLAG_UPDATE_CURRENT))
                .build();
        notificationManager.notify(NOTIFICATION_ID, notification);

        final String address = intent.getStringExtra(Devices.ADDRESS);
        Events.insert(context, NAME, address, position);
    }
}
 
Example #24
Source File: ScannerViewModel.java    From mcumgr-android with Apache License 2.0 5 votes vote down vote up
/**
 * Register for required broadcast receivers.
 */
private void registerBroadcastReceivers(@NonNull final Application application) {
    application.registerReceiver(mBluetoothStateBroadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    if (Utils.isMarshmallowOrAbove()) {
        application.registerReceiver(mLocationProviderChangedReceiver, new IntentFilter(LocationManager.MODE_CHANGED_ACTION));
    }
}
 
Example #25
Source File: SalaatAlarmReceiver.java    From PrayTime-Android with Apache License 2.0 5 votes vote down vote up
public void removePassiveLocationUpdates(Context context, PendingIntent pendingIntent) {
  LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
  try {
    locationManager.removeUpdates(pendingIntent);
  } catch (SecurityException se) {
    //do nothing. We should always have permision in order to reach this screen.
  }
}
 
Example #26
Source File: LocationHandler.java    From geoar-app with Apache License 2.0 5 votes vote down vote up
/**
 * Performs processes needed to enable location updates
 */
public static void onResume() {
	if (!listeners.isEmpty()) {
		if (!locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			InfoView.setStatus(R.string.gps_nicht_aktiviert, -1,
					gpsProviderInfo);
		}
		locationManager.requestLocationUpdates(
				LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
		LOG.debug("Requesting Location Updates");
	}
}
 
Example #27
Source File: DistanceFilterLocationProvider.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String key = LocationManager.KEY_LOCATION_CHANGED;
    Location location = (Location)intent.getExtras().get(key);
    if (location != null) {
        logger.debug("Single location update: " + location.toString());
        onPollStationaryLocation(location);
    }
}
 
Example #28
Source File: AndroidLocationEngineImpl.java    From mapbox-events-android with MIT License 5 votes vote down vote up
private String getBestProvider(int priority) {
  String provider = null;
  // Pick best provider only if user has not explicitly chosen passive mode
  if (priority != LocationEngineRequest.PRIORITY_NO_POWER) {
    provider = locationManager.getBestProvider(getCriteria(priority), true);
  }
  return provider != null ? provider : LocationManager.PASSIVE_PROVIDER;
}
 
Example #29
Source File: WebViewActivity.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void onCreate(Bundle icicle) {
	super.onCreate(icicle);
	setContentView(R.layout.main);
	browser = (WebView) findViewById(R.id.webkit);
	myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	browser.getSettings().setJavaScriptEnabled(true);
	browser.addJavascriptInterface(new Locater(), "locater");
	browser.loadUrl("file:///android_asset/geoweb1.html");
}
 
Example #30
Source File: LocationManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Enable or disable a single location provider.
 *
 * @param provider name of the provider
 * @param enabled true to enable the provider. False to disable the provider
 * @param userId the id of the user to set
 * @return true if the value was set, false on errors
 */
@Override
public boolean setProviderEnabledForUser(String provider, boolean enabled, int userId) {
    mContext.enforceCallingPermission(
            android.Manifest.permission.WRITE_SECURE_SETTINGS,
            "Requires WRITE_SECURE_SETTINGS permission");

    // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
    checkInteractAcrossUsersPermission(userId);

    // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
    // so we discourage its use
    if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;

    long identity = Binder.clearCallingIdentity();
    try {
        synchronized (mLock) {
            // No such provider exists
            if (!mProvidersByName.containsKey(provider)) return false;

            // If it is a test provider, do not write to Settings.Secure
            if (mMockProviders.containsKey(provider)) {
                setTestProviderEnabled(provider, enabled);
                return true;
            }

            // to ensure thread safety, we write the provider name with a '+' or '-'
            // and let the SettingsProvider handle it rather than reading and modifying
            // the list of enabled providers.
            String providerChange = (enabled ? "+" : "-") + provider;
            return Settings.Secure.putStringForUser(
                    mContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
                    providerChange, userId);
        }
    } finally {
        Binder.restoreCallingIdentity(identity);
    }
}