Example usage for android.location LocationManager PASSIVE_PROVIDER

List of usage examples for android.location LocationManager PASSIVE_PROVIDER

Introduction

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

Prototype

String PASSIVE_PROVIDER

To view the source code for android.location LocationManager PASSIVE_PROVIDER.

Click Source Link

Document

A special location provider for receiving locations without actually initiating a location fix.

Usage

From source file:com.vonglasow.michael.satstat.MapSectionFragment.java

/**
 * Updates the list of styles to use for the location providers.
 * //from  www  .  ja v a 2 s .  c  o m
 * This method updates the internal list of styles to use for displaying
 * locations on the map, assigning a style to each location provider.
 * Styles that are defined in {@link SharedPreferences} are preserved. If
 * none are defined, the GPS location provider is assigned the red style
 * and the network location provider is assigned the blue style. The
 * passive location provider is not assigned a style, as it does not send
 * any locations of its own. Other location providers are assigned one of
 * the following styles: green, orange, purple. If there are more location
 * providers than styles, the same style (including red and blue) can be
 * assigned to multiple providers. The mapping is written to 
 * SharedPreferences so that it will be preserved even as available
 * location providers change.
 */
public void updateLocationProviderStyles() {
    //FIXME: move code into assignLocationProviderStyle and use that
    List<String> allProviders = mainActivity.locationManager.getAllProviders();
    allProviders.remove(LocationManager.PASSIVE_PROVIDER);
    if (allProviders.contains(LocationManager.GPS_PROVIDER)) {
        providerStyles.put(LocationManager.GPS_PROVIDER,
                mainActivity.mSharedPreferences.getString(
                        SettingsActivity.KEY_PREF_LOC_PROV_STYLE + LocationManager.GPS_PROVIDER,
                        LOCATION_PROVIDER_RED));
        mAvailableProviderStyles.remove(LOCATION_PROVIDER_RED);
        allProviders.remove(LocationManager.GPS_PROVIDER);
    }
    if (allProviders.contains(LocationManager.NETWORK_PROVIDER)) {
        providerStyles.put(LocationManager.NETWORK_PROVIDER,
                mainActivity.mSharedPreferences.getString(
                        SettingsActivity.KEY_PREF_LOC_PROV_STYLE + LocationManager.NETWORK_PROVIDER,
                        LOCATION_PROVIDER_BLUE));
        mAvailableProviderStyles.remove(LOCATION_PROVIDER_BLUE);
        allProviders.remove(LocationManager.NETWORK_PROVIDER);
    }
    for (String prov : allProviders) {
        if (mAvailableProviderStyles.isEmpty())
            mAvailableProviderStyles.addAll(Arrays.asList(LOCATION_PROVIDER_STYLES));
        providerStyles.put(prov, mainActivity.mSharedPreferences
                .getString(SettingsActivity.KEY_PREF_LOC_PROV_STYLE + prov, mAvailableProviderStyles.get(0)));
        mAvailableProviderStyles.remove(providerStyles.get(prov));
    }
    ;
    SharedPreferences.Editor spEditor = mainActivity.mSharedPreferences.edit();
    for (String prov : providerStyles.keySet())
        spEditor.putString(SettingsActivity.KEY_PREF_LOC_PROV_STYLE + prov, providerStyles.get(prov));
    spEditor.commit();
}

From source file:de.grobox.liberario.DirectionsFragment.java

private void pressGpsButton() {
    List<String> providers = locationManager.getProviders(true);

    for (String provider : providers) {
        // Register the listener with the Location Manager to receive location updates
        locationManager.requestSingleUpdate(provider, this, null);

        Log.d(getClass().getSimpleName(), "Register provider for location updates: " + provider);
    }// ww  w .j  a v a2  s. c  om

    // check if there is a non-passive provider available
    if (providers.size() == 0
            || (providers.size() == 1 && providers.get(0).equals(LocationManager.PASSIVE_PROVIDER))) {
        removeUpdates();
        Toast.makeText(getActivity(), getResources().getString(R.string.error_no_location_provider),
                Toast.LENGTH_LONG).show();

        return;
    }

    // show GPS button blinking
    final Animation animation = new AlphaAnimation(1, 0);
    animation.setDuration(500);
    animation.setInterpolator(new LinearInterpolator());
    animation.setRepeatCount(Animation.INFINITE);
    animation.setRepeatMode(Animation.REVERSE);
    mView.findViewById(R.id.fromStatusButton).setAnimation(animation);

    mGpsPressed = true;
    gps_loc = null;
}

From source file:com.vonglasow.michael.satstat.ui.MapSectionFragment.java

/**
 * Updates the list of styles to use for the location providers.
 * /* ww  w  .j  a  va2s. co  m*/
 * This method updates the internal list of styles to use for displaying
 * locations on the map, assigning a style to each location provider.
 * Styles that are defined in {@link SharedPreferences} are preserved. If
 * none are defined, the GPS location provider is assigned the red style
 * and the network location provider is assigned the blue style. The
 * passive location provider is not assigned a style, as it does not send
 * any locations of its own. Other location providers are assigned one of
 * the following styles: green, orange, purple. If there are more location
 * providers than styles, the same style (including red and blue) can be
 * assigned to multiple providers. The mapping is written to 
 * SharedPreferences so that it will be preserved even as available
 * location providers change.
 */
public void updateLocationProviderStyles() {
    //FIXME: move code into assignLocationProviderStyle and use that
    List<String> allProviders = mainActivity.locationManager.getAllProviders();
    allProviders.remove(LocationManager.PASSIVE_PROVIDER);
    if (allProviders.contains(LocationManager.GPS_PROVIDER)) {
        providerStyles.put(LocationManager.GPS_PROVIDER, mainActivity.mSharedPreferences.getString(
                Const.KEY_PREF_LOC_PROV_STYLE + LocationManager.GPS_PROVIDER, Const.LOCATION_PROVIDER_RED));
        mAvailableProviderStyles.remove(Const.LOCATION_PROVIDER_RED);
        allProviders.remove(LocationManager.GPS_PROVIDER);
    }
    if (allProviders.contains(LocationManager.NETWORK_PROVIDER)) {
        providerStyles.put(LocationManager.NETWORK_PROVIDER,
                mainActivity.mSharedPreferences.getString(
                        Const.KEY_PREF_LOC_PROV_STYLE + LocationManager.NETWORK_PROVIDER,
                        Const.LOCATION_PROVIDER_BLUE));
        mAvailableProviderStyles.remove(Const.LOCATION_PROVIDER_BLUE);
        allProviders.remove(LocationManager.NETWORK_PROVIDER);
    }
    for (String prov : allProviders) {
        if (mAvailableProviderStyles.isEmpty())
            mAvailableProviderStyles.addAll(Arrays.asList(Const.LOCATION_PROVIDER_STYLES));
        providerStyles.put(prov, mainActivity.mSharedPreferences.getString(Const.KEY_PREF_LOC_PROV_STYLE + prov,
                mAvailableProviderStyles.get(0)));
        mAvailableProviderStyles.remove(providerStyles.get(prov));
    }
    ;
    SharedPreferences.Editor spEditor = mainActivity.mSharedPreferences.edit();
    for (String prov : providerStyles.keySet())
        spEditor.putString(Const.KEY_PREF_LOC_PROV_STYLE + prov, providerStyles.get(prov));
    spEditor.commit();
}

From source file:net.mypapit.mobile.myrepeater.RepeaterListActivity.java

public boolean isLocationEnabled(Context context) {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    String provider = lm.getBestProvider(new Criteria(), true);
    return (!TextUtils.isEmpty(provider) && !LocationManager.PASSIVE_PROVIDER.equals(provider));

}

From source file:plugin.google.maps.GoogleMaps.java

@SuppressWarnings("unused")
private void getMyLocation(final JSONArray args, final CallbackContext callbackContext) throws JSONException {

    LocationManager locationManager = (LocationManager) this.activity
            .getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    if (providers.size() == 0) {
        JSONObject result = new JSONObject();
        result.put("status", false);
        result.put("error_code", "not_available");
        result.put("error_message",
                "Since this device does not have any location provider, this app can not detect your location.");
        callbackContext.error(result);/*w  ww  . jav  a 2  s.c  om*/
        return;
    }

    // enableHighAccuracy = true -> PRIORITY_HIGH_ACCURACY
    // enableHighAccuracy = false -> PRIORITY_BALANCED_POWER_ACCURACY

    JSONObject params = args.getJSONObject(0);
    boolean isHigh = false;
    if (params.has("enableHighAccuracy")) {
        isHigh = params.getBoolean("enableHighAccuracy");
    }
    final boolean enableHighAccuracy = isHigh;

    String provider = null;
    if (enableHighAccuracy == true) {
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
        }
    } else {
        if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
            provider = LocationManager.PASSIVE_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            provider = LocationManager.NETWORK_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            provider = LocationManager.GPS_PROVIDER;
        }
    }
    if (provider == null) {
        //Ask the user to turn on the location services.
        AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
        builder.setTitle("Improve location accuracy");
        builder.setMessage("To enhance your Maps experience:\n\n" + " - Enable Google apps location access\n\n"
                + " - Turn on GPS and mobile network location");
        builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Launch settings, allowing user to make a change
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                activity.startActivity(intent);

                JSONObject result = new JSONObject();
                try {
                    result.put("status", false);
                    result.put("error_code", "open_settings");
                    result.put("error_message", "User opened the settings of location service. So try again.");
                } catch (JSONException e) {
                }
                callbackContext.error(result);
            }
        });
        builder.setNegativeButton("Skip", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //No location service, no Activity
                dialog.dismiss();

                JSONObject result = new JSONObject();
                try {
                    result.put("status", false);
                    result.put("error_code", "service_denied");
                    result.put("error_message", "This app has rejected to use Location Services.");
                } catch (JSONException e) {
                }
                callbackContext.error(result);
            }
        });
        builder.create().show();
        return;
    }

    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        JSONObject result = PluginUtil.location2Json(location);
        result.put("status", true);
        callbackContext.success(result);
        return;
    }

    PluginResult tmpResult = new PluginResult(PluginResult.Status.NO_RESULT);
    tmpResult.setKeepCallback(true);
    callbackContext.sendPluginResult(tmpResult);

    locationClient = new LocationClient(this.activity, new ConnectionCallbacks() {

        @Override
        public void onConnected(Bundle bundle) {
            LocationRequest request = new LocationRequest();
            int priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
            if (enableHighAccuracy) {
                priority = LocationRequest.PRIORITY_HIGH_ACCURACY;
            }
            request.setPriority(priority);
            locationClient.requestLocationUpdates(request, new LocationListener() {

                @Override
                public void onLocationChanged(Location location) {
                    JSONObject result;
                    try {
                        result = PluginUtil.location2Json(location);
                        result.put("status", true);
                        callbackContext.success(result);
                    } catch (JSONException e) {
                    }
                    locationClient.disconnect();
                }

            });
        }

        @Override
        public void onDisconnected() {
        }

    }, new OnConnectionFailedListener() {

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            int errorCode = connectionResult.getErrorCode();
            String errorMsg = GooglePlayServicesUtil.getErrorString(errorCode);
            PluginResult result = new PluginResult(PluginResult.Status.ERROR, errorMsg);
            callbackContext.sendPluginResult(result);
        }

    });
    locationClient.connect();
}

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;
            }/*w w  w  . ja  v  a 2  s  .co  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:com.scoreflex.Scoreflex.java

/**
 * Returns the Location as set in {@link setLocation(Location)} or the best
 * last known location of the {@link LocationManager} or null if permission
 * was not given.//w  w  w.  j a  va 2s  . c o  m
 */

public static Location getLocation() {
    if (null != sLocation)
        return sLocation;

    Context applicationContext = getApplicationContext();

    if (applicationContext == null)
        return null;

    LocationManager locationManager = (LocationManager) applicationContext
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        Location locations[] = { locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER),
                locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER),
                locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER), };

        Location best = null;
        for (int i = 0; i < locations.length; i++) {

            // If this location is null, discard
            if (null == locations[i])
                continue;

            // If we have no best yet, use this first location
            if (null == best) {
                best = locations[i];
                continue;
            }

            // If this location is significantly older, discard
            long timeDelta = locations[i].getTime() - best.getTime();
            if (timeDelta < -1000 * 60 * 2)
                continue;

            // If we have no accuracy, discard
            if (0 == locations[i].getAccuracy())
                continue;

            // If this location is less accurate, discard
            if (best.getAccuracy() < locations[i].getAccuracy())
                continue;

            best = locations[i];
        }

        return best;
    } catch (java.lang.SecurityException e) {
        // Missing permission;
        return null;
    }
}

From source file:com.vonglasow.michael.satstat.MainActivity.java

/**
 * Updates the list of styles to use for the location providers.
 * // www  .  ja  va 2s .co m
 * This method updates the internal list of styles to use for displaying
 * locations on the map, assigning a style to each location provider.
 * Styles that are defined in {@link SharedPreferences} are preserved. If
 * none are defined, the GPS location provider is assigned the red style
 * and the network location provider is assigned the blue style. The
 * passive location provider is not assigned a style, as it does not send
 * any locations of its own. Other location providers are assigned one of
 * the following styles: green, orange, purple. If there are more location
 * providers than styles, the same style (including red and blue) can be
 * assigned to multiple providers. The mapping is written to 
 * SharedPreferences so that it will be preserved even as available
 * location providers change.
 */
public static void updateLocationProviderStyles() {
    //FIXME: move code into assignLocationProviderStyle and use that
    List<String> allProviders = mLocationManager.getAllProviders();
    allProviders.remove(LocationManager.PASSIVE_PROVIDER);
    if (allProviders.contains(LocationManager.GPS_PROVIDER)) {
        providerStyles.put(LocationManager.GPS_PROVIDER,
                mSharedPreferences.getString(
                        SettingsActivity.KEY_PREF_LOC_PROV_STYLE + LocationManager.GPS_PROVIDER,
                        LOCATION_PROVIDER_RED));
        mAvailableProviderStyles.remove(LOCATION_PROVIDER_RED);
        allProviders.remove(LocationManager.GPS_PROVIDER);
    }
    if (allProviders.contains(LocationManager.NETWORK_PROVIDER)) {
        providerStyles.put(LocationManager.NETWORK_PROVIDER,
                mSharedPreferences.getString(
                        SettingsActivity.KEY_PREF_LOC_PROV_STYLE + LocationManager.NETWORK_PROVIDER,
                        LOCATION_PROVIDER_BLUE));
        mAvailableProviderStyles.remove(LOCATION_PROVIDER_BLUE);
        allProviders.remove(LocationManager.NETWORK_PROVIDER);
    }
    for (String prov : allProviders) {
        if (mAvailableProviderStyles.isEmpty())
            mAvailableProviderStyles.addAll(Arrays.asList(LOCATION_PROVIDER_STYLES));
        providerStyles.put(prov, mSharedPreferences.getString(SettingsActivity.KEY_PREF_LOC_PROV_STYLE + prov,
                mAvailableProviderStyles.get(0)));
        mAvailableProviderStyles.remove(providerStyles.get(prov));
    }
    ;
    SharedPreferences.Editor spEditor = mSharedPreferences.edit();
    for (String prov : providerStyles.keySet())
        spEditor.putString(SettingsActivity.KEY_PREF_LOC_PROV_STYLE + prov, providerStyles.get(prov));
    spEditor.commit();
}