Example usage for android.location LocationManager isProviderEnabled

List of usage examples for android.location LocationManager isProviderEnabled

Introduction

In this page you can find the example usage for android.location LocationManager isProviderEnabled.

Prototype

public boolean isProviderEnabled(String provider) 

Source Link

Document

Returns the current enabled/disabled status of the given provider.

Usage

From source file:com.trailbehind.android.iburn.map.MapActivity.java

/**
 * Check gps provider./*from  ww w.j a v a2  s  .co m*/
 */
private void checkGPSProvider() {
    final LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        mProgressBar.setVisibility(View.GONE);
        mMessageTextView.setText(R.string.error_gps_disabled);
        mMessageTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    mVibrator.vibrate(50);

                    final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(intent);
                } catch (Exception e) {
                    // we dont care
                }
            }
        });

        UIUtils.showPanel(getBaseContext(), mMessagePanel, false);
    } else if (Globals.sCurrentGPSLocation == null) {
        mProgressBar.setVisibility(View.VISIBLE);
        mMessageTextView.setText(R.string.msg_locating);

        UIUtils.showPanel(getBaseContext(), mMessagePanel, false);
    } else {
        UIUtils.hidePanel(getBaseContext(), mMessagePanel, false);
    }
}

From source file:com.appdupe.flamer.LoginUsingFacebook.java

@Override
protected void onResume() {
    super.onResume();
    checkPlayServices();/*ww w .j ava2  s  .co m*/
    LocationManager locationManagerresume = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (locationManagerresume.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        newLocationFinder = new LocationFinder();
        newLocationFinder.getLocation(LoginUsingFacebook.this, mLocationResult);
    } else {
        showGPSDisabledAlertToUser();

    }
}

From source file:org.csp.everyaware.offline.Map.java

@Override
protected void onStart() {
    super.onStart();

    // This verification should be done during onStart() because the system calls
    // this method when the user returns to the activity, which ensures the desired
    // location provider is enabled each time the activity resumes from the stopped state.
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (!gpsEnabled) {
        // Build an alert dialog here that requests that the user enable
        // the location services, then when the user clicks the "OK" button,
        // call enableLocationSettings()
    }/*w w w .  j ava2 s .co m*/
}

From source file:org.rebo.app.TileMap.java

public void toggleLocation(LocationHandler.Mode setMode) {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (setMode == null) {
        LocationHandler.Mode mode = mLocation.getMode();

        switch (mode) {
        case OFF:
            if (routeSearch != null && routeSearch.getDestinationPoint() != null
                    && mode != LocationHandler.Mode.NAV) {
                setMode = LocationHandler.Mode.NAV;
            } else {
                setMode = SNAP;//from w ww.  j a  v  a  2s  .  c o m
            }
            break;
        case NAV:
        case SNAP:
            setMode = LocationHandler.Mode.OFF;
            break;
        default:
            setMode = SNAP;
            break;
        }
    }
    //Ask if GPS is activated?
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();
        if (setMode != LocationHandler.Mode.OFF) {
            mLocation.setMode(LocationHandler.Mode.OFF);
            mLocationFab.setBackgroundTintList(
                    getBaseContext().getResources().getColorStateList(R.color.disabledBackgroundLight));
            mLocationFab.setImageResource(R.drawable.ic_location_disabled_white_24dp);
        }
    } else {
        boolean success = false;
        switch (setMode) {
        case SHOW:
            if (success = mLocation.setMode(LocationHandler.Mode.SHOW)) {
                mLocationFab.setBackgroundTintList(
                        getBaseContext().getResources().getColorStateList(R.color.colorSecondAccent));
                mLocationFab.setImageResource(R.drawable.ic_find_location_white_24dp);
            }
            break;
        case SNAP:
            if (success = mLocation.setMode(SNAP)) {
                mLocationFab.setBackgroundTintList(
                        getBaseContext().getResources().getColorStateList(R.color.colorAccent));
                mLocationFab.setImageResource(R.drawable.ic_my_location_white_24dp);
            }
            break;
        case OFF:
            if (success = mLocation.setMode(LocationHandler.Mode.OFF)) {
                mLocationFab.setBackgroundTintList(
                        getBaseContext().getResources().getColorStateList(R.color.disabledBackgroundLight));
                mLocationFab.setImageResource(R.drawable.ic_location_disabled_white_24dp);
            }
            break;
        case NAV:
            if (routeSearch != null && routeSearch.getDestinationPoint() != null) {
                if (success = mLocation.setMode(LocationHandler.Mode.NAV)) {
                    mLocationFab.setBackgroundTintList(
                            getBaseContext().getResources().getColorStateList(R.color.colorAccent));
                    mLocationFab.setImageResource(R.drawable.ic_navigation_white_24dp);
                }
                toggleCompass(Compass.Mode.NAV);
                mCompass.setTilt(80);
            }
            break;
        default:
            success = true;
            break;
        }
        if (!success) {
            mLocationFab.setBackgroundTintList(
                    getBaseContext().getResources().getColorStateList(R.color.disabledBackgroundLight));
            mLocationFab.setImageResource(R.drawable.ic_location_searching_white_24dp);
        }
    }
}

From source file:org.telegram.ui.ThemeActivity.java

private void updateSunTime(Location lastKnownLocation, boolean forceUpdate) {
    LocationManager locationManager = (LocationManager) ApplicationLoader.applicationContext
            .getSystemService(Context.LOCATION_SERVICE);
    if (Build.VERSION.SDK_INT >= 23) {
        Activity activity = getParentActivity();
        if (activity != null) {
            if (activity.checkSelfPermission(
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION }, 2);
                return;
            }/*from   w ww.j  a va  2 s  . c  o m*/
        }
    }
    if (getParentActivity() != null) {
        if (!getParentActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) {
            return;
        }
        try {
            LocationManager lm = (LocationManager) ApplicationLoader.applicationContext
                    .getSystemService(Context.LOCATION_SERVICE);
            if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setMessage(LocaleController.getString("GpsDisabledAlert", R.string.GpsDisabledAlert));
                builder.setPositiveButton(
                        LocaleController.getString("ConnectingToProxyEnable", R.string.ConnectingToProxyEnable),
                        (dialog, id) -> {
                            if (getParentActivity() == null) {
                                return;
                            }
                            try {
                                getParentActivity().startActivity(
                                        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            } catch (Exception ignore) {

                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
                return;
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    }
    try {
        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
    if (lastKnownLocation == null || forceUpdate) {
        startLocationUpdate();
        if (lastKnownLocation == null) {
            return;
        }
    }
    Theme.autoNightLocationLatitude = lastKnownLocation.getLatitude();
    Theme.autoNightLocationLongitude = lastKnownLocation.getLongitude();
    int time[] = SunDate.calculateSunriseSunset(Theme.autoNightLocationLatitude,
            Theme.autoNightLocationLongitude);
    Theme.autoNightSunriseTime = time[0];
    Theme.autoNightSunsetTime = time[1];
    Theme.autoNightCityName = null;
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    Theme.autoNightLastSunCheckDay = calendar.get(Calendar.DAY_OF_MONTH);
    Utilities.globalQueue.postRunnable(() -> {
        String name;
        try {
            Geocoder gcd = new Geocoder(ApplicationLoader.applicationContext, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(Theme.autoNightLocationLatitude,
                    Theme.autoNightLocationLongitude, 1);
            if (addresses.size() > 0) {
                name = addresses.get(0).getLocality();
            } else {
                name = null;
            }
        } catch (Exception ignore) {
            name = null;
        }
        final String nameFinal = name;
        AndroidUtilities.runOnUIThread(() -> {
            Theme.autoNightCityName = nameFinal;
            if (Theme.autoNightCityName == null) {
                Theme.autoNightCityName = String.format("(%.06f, %.06f)", Theme.autoNightLocationLatitude,
                        Theme.autoNightLocationLongitude);
            }
            Theme.saveAutoNightThemeConfig();
            if (listView != null) {
                RecyclerListView.Holder holder = (RecyclerListView.Holder) listView
                        .findViewHolderForAdapterPosition(scheduleUpdateLocationRow);
                if (holder != null && holder.itemView instanceof TextSettingsCell) {
                    ((TextSettingsCell) holder.itemView).setTextAndValue(LocaleController
                            .getString("AutoNightUpdateLocation", R.string.AutoNightUpdateLocation),
                            Theme.autoNightCityName, false);
                }
            }
        });
    });
    RecyclerListView.Holder holder = (RecyclerListView.Holder) listView
            .findViewHolderForAdapterPosition(scheduleLocationInfoRow);
    if (holder != null && holder.itemView instanceof TextInfoPrivacyCell) {
        ((TextInfoPrivacyCell) holder.itemView).setText(getLocationSunString());
    }
    if (Theme.autoNightScheduleByLocation && Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SCHEDULED) {
        Theme.checkAutoNightThemeConditions();
    }
}

From source file:piuk.blockchain.android.WalletApplication.java

public boolean isGeoEnabled() {
    LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}

From source file:com.mparticle.MParticle.java

/**
 * Enables location tracking given a provider and update frequency criteria. The provider must
 * be available and the correct permissions must have been requested within your application's manifest XML file.
 *
 * @param provider    the provider key/*w w  w.j ava  2  s.  co m*/
 * @param minTime     the minimum time (in milliseconds) to trigger an update
 * @param minDistance the minimum distance (in meters) to trigger an update
 */
public void enableLocationTracking(String provider, long minTime, long minDistance) {
    if (mConfigManager.isEnabled()) {
        try {
            LocationManager locationManager = (LocationManager) mAppContext
                    .getSystemService(Context.LOCATION_SERVICE);
            if (!locationManager.isProviderEnabled(provider)) {
                ConfigManager.log(LogLevel.ERROR, "That requested location provider is not available");
                return;
            }

            if (null == mLocationListener) {
                mLocationListener = new MPLocationListener(this);
            } else {
                // clear the location listener, so it can be added again
                locationManager.removeUpdates(mLocationListener);
            }
            locationManager.requestLocationUpdates(provider, minTime, minDistance, mLocationListener);
            SharedPreferences.Editor editor = mPreferences.edit();
            editor.putString(PrefKeys.LOCATION_PROVIDER, provider).putLong(PrefKeys.LOCATION_MINTIME, minTime)
                    .putLong(PrefKeys.LOCATION_MINDISTANCE, minDistance).apply();

        } catch (SecurityException e) {
            ConfigManager.log(LogLevel.ERROR,
                    "The app must require the appropriate permissions to track location using this provider");
        }
    }
}

From source file:org.getlantern.firetweet.activity.support.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 *//*from w  ww .j  a  v a 2s. c om*/
private boolean startLocationUpdateIfEnabled() {
    final LocationManager lm = mLocationManager;
    final boolean attachLocation = mPreferences.getBoolean(KEY_ATTACH_LOCATION, false);
    if (!attachLocation) {
        lm.removeUpdates(this);
        return false;
    }
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = lm.getBestProvider(criteria, true);
    if (provider != null) {
        mLocationText.setText(R.string.getting_location);
        lm.requestLocationUpdates(provider, 0, 0, this);
        final Location location;
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = lm.getLastKnownLocation(provider);
        }
        if (location != null) {
            onLocationChanged(location);
        }
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != null;
}

From source file:org.mariotaku.twidere.activity.support.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 *///from  w w w  . j  a va 2 s .co m
private boolean startLocationUpdateIfEnabled() {
    final LocationManager lm = mLocationManager;
    final boolean attachLocation = mPreferences.getBoolean(KEY_ATTACH_LOCATION);
    if (!attachLocation) {
        lm.removeUpdates(this);
        return false;
    }
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = lm.getBestProvider(criteria, true);
    if (provider != null) {
        mLocationText.setText(R.string.getting_location);
        lm.requestLocationUpdates(provider, 0, 0, this);
        final Location location;
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = lm.getLastKnownLocation(provider);
        }
        if (location != null) {
            onLocationChanged(location);
        }
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != null;
}

From source file:com.mobilyzer.util.PhoneUtils.java

/**
 * Lazily initializes the location manager.
 *
 * As a side effect, assigns locationManager and locationProviderName.
 *///from  ww  w .  jav a2 s.  c  o m
private synchronized void initLocation() {
    if (locationManager == null) {
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        Criteria criteriaCoarse = new Criteria();
        /* "Coarse" accuracy means "no need to use GPS".
         * Typically a gShots phone would be located in a building,
         * and GPS may not be able to acquire a location.
         * We only care about the location to determine the country,
         * so we don't need a super accurate location, cell/wifi is good enough.
         */
        criteriaCoarse.setAccuracy(Criteria.ACCURACY_COARSE);
        criteriaCoarse.setPowerRequirement(Criteria.POWER_LOW);
        String providerName = manager.getBestProvider(criteriaCoarse, /*enabledOnly=*/true);

        List<String> providers = manager.getAllProviders();
        for (String providerNameIter : providers) {
            try {
                LocationProvider provider = manager.getProvider(providerNameIter);
            } catch (SecurityException se) {
                // Not allowed to use this provider
                Logger.w("Unable to use provider " + providerNameIter);
                continue;
            }
            Logger.i(providerNameIter + ": "
                    + (manager.isProviderEnabled(providerNameIter) ? "enabled" : "disabled"));
        }

        /* Make sure the provider updates its location.
         * Without this, we may get a very old location, even a
         * device powercycle may not update it.
         * {@see android.location.LocationManager.getLastKnownLocation}.
         */
        manager.requestLocationUpdates(providerName, /*minTime=*/0, /*minDistance=*/0,
                new LoggingLocationListener(), Looper.getMainLooper());
        locationManager = manager;
        locationProviderName = providerName;
    }
    assert locationManager != null;
    assert locationProviderName != null;
}