Example usage for android.location LocationManager GPS_PROVIDER

List of usage examples for android.location LocationManager GPS_PROVIDER

Introduction

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

Prototype

String GPS_PROVIDER

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

Click Source Link

Document

Name of the GPS location provider.

Usage

From source file:com.androzic.location.LocationService.java

private void updateProvider(final ILocationListener callback) {
    if (gpsStatus == GPS_OFF)
        callback.onProviderDisabled(LocationManager.GPS_PROVIDER);
    else//from  w  ww .  j a v a2  s .c o  m
        callback.onProviderEnabled(LocationManager.GPS_PROVIDER);
}

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

/**
 * Updates internal data structures when the user's selection of location providers has changed.
 * @param providers The new set of location providers
 *//*w ww  .  j a v  a 2 s. com*/
public void onLocationProvidersChanged(Set<String> providers) {
    Context context = this.getContext();
    List<String> allProviders = mainActivity.locationManager.getAllProviders();
    ArrayList<String> removedProviders = new ArrayList<String>();

    for (String pr : providerLocations.keySet())
        if (!providers.contains(pr))
            removedProviders.add(pr);

    // remove cached locations and invalidators for providers which are no longer selected
    for (String pr : removedProviders) {
        providerLocations.remove(pr);
        providerInvalidators.remove(pr);
    }

    // ensure there is a cached location for each chosen provider (can be null)
    for (String pr : providers) {
        if ((allProviders.indexOf(pr) >= 0) && !providerLocations.containsKey(pr)) {
            Location location = new Location("");
            providerLocations.put(pr, location);
        }
    }

    // add overlays
    updateLocationProviderStyles();

    mapCircles = new HashMap<String, Circle>();
    mapMarkers = new HashMap<String, Marker>();

    Log.d(TAG, "Provider location cache: " + providerLocations.keySet().toString());

    Layers layers = mapMap.getLayerManager().getLayers();

    // remove all layers other than tile render layer from map
    for (Layer layer : layers)
        if (!(layer instanceof TileRendererLayer) && !(layer instanceof TileDownloadLayer)) {
            layer.onDestroy();
            layers.remove(layer);
        }

    for (String pr : providers) {
        // no invalidator for GPS, which is invalidated through GPS status
        if ((!pr.equals(LocationManager.GPS_PROVIDER)) && (providerInvalidators.get(pr)) == null) {
            final String provider = pr;
            final Context ctx = context;
            providerInvalidators.put(pr, new Runnable() {
                private String mProvider = provider;

                @Override
                public void run() {
                    Location location = providerLocations.get(mProvider);
                    if (location != null)
                        markLocationAsStale(location);
                    applyLocationProviderStyle(ctx, mProvider, Const.LOCATION_PROVIDER_GRAY);
                }
            });
        }

        String styleName = assignLocationProviderStyle(pr);
        LatLong latLong;
        float acc;
        boolean visible;
        if ((providerLocations.get(pr) != null) && (providerLocations.get(pr).getProvider() != "")) {
            latLong = new LatLong(providerLocations.get(pr).getLatitude(),
                    providerLocations.get(pr).getLongitude());
            if (providerLocations.get(pr).hasAccuracy())
                acc = providerLocations.get(pr).getAccuracy();
            else
                acc = 0;
            visible = true;
            if (isLocationStale(providerLocations.get(pr)))
                styleName = Const.LOCATION_PROVIDER_GRAY;
            Log.d("MainActivity", pr + " has " + latLong.toString());
        } else {
            latLong = new LatLong(0, 0);
            acc = 0;
            visible = false;
            Log.d("MainActivity", pr + " has no location, hiding");
        }

        // Circle layer
        Resources res = context.getResources();
        TypedArray style = res
                .obtainTypedArray(res.getIdentifier(styleName, "array", context.getPackageName()));
        Paint fill = AndroidGraphicFactory.INSTANCE.createPaint();
        float density = context.getResources().getDisplayMetrics().density;
        fill.setColor(style.getColor(Const.STYLE_FILL, R.color.circle_gray_fill));
        fill.setStyle(Style.FILL);
        Paint stroke = AndroidGraphicFactory.INSTANCE.createPaint();
        stroke.setColor(style.getColor(Const.STYLE_STROKE, R.color.circle_gray_stroke));
        stroke.setStrokeWidth(Math.max(1.5f * density, 1));
        stroke.setStyle(Style.STROKE);
        Circle circle = new Circle(latLong, acc, fill, stroke);
        mapCircles.put(pr, circle);
        layers.add(circle);
        circle.setVisible(visible);

        // Marker layer
        Drawable drawable = style.getDrawable(Const.STYLE_MARKER);
        Bitmap bitmap = AndroidGraphicFactory.convertToBitmap(drawable);
        Marker marker = new Marker(latLong, bitmap, 0, -bitmap.getHeight() * 10 / 24);
        mapMarkers.put(pr, marker);
        layers.add(marker);
        marker.setVisible(visible);
        style.recycle();
    }

    // move layers into view
    updateMap();
}

From source file:com.crearo.gpslogger.GpsLoggingService.java

/**
 * This method is called periodically to determine whether the cell tower /
 * gps providers have been enabled, and sets class level variables to those
 * values./*from  ww  w . j  a v  a 2 s. com*/
 */
private void checkTowerAndGpsStatus() {
    Session.setTowerEnabled(towerLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
    Session.setGpsEnabled(gpsLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
}

From source file:com.androzic.location.LocationService.java

private void updateGpsStatus(final int status, final int fsats, final int tsats) {
    gpsStatus = status;/*  www.  j a  v a  2  s .  com*/
    updateNotification();
    final Handler handler = new Handler();
    for (final ILocationListener callback : locationCallbacks) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onGpsStatusChanged(LocationManager.GPS_PROVIDER, status, fsats, tsats);
            }
        });
    }
    final int n = locationRemoteCallbacks.beginBroadcast();
    for (int i = 0; i < n; i++) {
        final ILocationCallback callback = locationRemoteCallbacks.getBroadcastItem(i);
        try {
            callback.onGpsStatusChanged(LocationManager.GPS_PROVIDER, status, fsats, tsats);
        } catch (RemoteException e) {
            Log.e(TAG, "Status broadcast error", e);
        }
    }
    locationRemoteCallbacks.finishBroadcast();
    Log.d(TAG, "GPS status dispatched: " + (locationCallbacks.size() + n));
}

From source file:com.eeshana.icstories.activities.UploadVideoActivity.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE && resultCode == 0) {
        String provider = Settings.Secure.getString(getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (provider != null) {
            //Log.v(TAG, " Location providers: "+provider);
            //Start searching for location and update the location text when update available. 
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        } else {//w  w w  . ja va 2  s. co m
            //Users did not switch on the GPS
            //   showCustomToast.showToast(SharePhotoActivity.this, "  ");
            locationDialog.show();
        }
    }
}

From source file:com.tdispatch.passenger.fragment.ControlCenterFragment.java

protected void moveMapToLocation(LatLng location, Boolean disableAnimation, Boolean resetCamera) {

    MapFragment mapFragment = (MapFragment) mFragmentManager.findFragmentById(R.id.map_fragment);
    if (mapFragment != null) {
        GoogleMap map = mapFragment.getMap();
        if (map != null) {

            if (location == null) {
                Location tmp = map.getMyLocation();
                if (tmp != null) {
                    location = new LatLng(tmp.getLatitude(), tmp.getLongitude());
                }/* w  w w  .j  a  v  a 2s . co m*/
            }

            if (location == null) {
                Location lastKnownLoc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (lastKnownLoc == null) {
                    lastKnownLoc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }

                if (lastKnownLoc != null) {
                    location = new LatLng(lastKnownLoc.getLatitude(), lastKnownLoc.getLongitude());
                }
            }

            if (location != null) {
                CameraUpdate cameraUpdate;
                if (resetCamera) {
                    CameraPosition cameraPosition = new CameraPosition.Builder().target(location).zoom(15f)
                            .bearing(0f).tilt(0).build();
                    cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                } else {
                    cameraUpdate = CameraUpdateFactory.newLatLng(location);
                }

                if (disableAnimation) {
                    map.moveCamera(cameraUpdate);
                } else {
                    map.animateCamera(cameraUpdate);
                }
            } else {
                NoLocationDialogFragment frag = NoLocationDialogFragment.newInstance(
                        GenericDialogFragment.DIALOG_TYPE_ERROR,
                        getString(R.string.unable_to_get_current_location_body),
                        getString(R.string.unable_to_get_current_location_button_show_settings));
                frag.setTargetFragment(mMe, 0);
                frag.show(((FragmentActivity) mParentActivity).getSupportFragmentManager(), "nolocationdialog");
            }
        }
    }
}

From source file:com.raddapp.radika.raddappv001.GpsLoggingService.java

/**
 * This method is called periodically to determine whether the cell tower /
 * gps providers have been enabled, and sets class level variables to those
 * values.//  w ww . j  a  v  a 2  s .  c om
 */
private void CheckTowerAndGpsStatus() {
    Log.d("GPSLOGSERV 101", "CheckTowerAndGpsStatus");
    Session.setTowerEnabled(towerLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
    Session.setGpsEnabled(gpsLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
}

From source file:net.kidlogger.kidlogger.KLService.java

private void startGpsUpdates() {
    long minTime = 0;
    float minDist = 0;

    try {//w w w . j av  a 2 s  .  c o m
        minTime = Long.parseLong(Settings.getGpsUpdatesTime(this));
        minDist = Float.parseFloat(Settings.getMinDistance(this));
    } catch (NumberFormatException e) {
        minTime = MIN * 5L;
        minDist = 20.0f;
        app.logError(CN + "startGpsUpdates", e.toString());
    }

    //List<String> locProviders = locMngr.getAllProviders();      
    locListener = new KidLocListener();

    if (locMngr.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime * MIN, minDist, locListener);
        //Log.i(CN, "GPS location");
    } else if (locMngr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locMngr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime * MIN, minDist, locListener);
        //Log.i(CN, "Network location");
    } else
        gpsOn = false;

    /*
    if(gpsOn)
       locMngr.removeUpdates(onLocationChange);
            
    try{
       locMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime * MIN,
       minDist, onLocationChange);
       //locMngr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime * MIN,
       //      minDist, onLocationChange);
       Log.i("KLS", "Min time: " + minTime + "min dist: " + minDist);
    }catch(IllegalArgumentException e){
       app.logError(CN + "startGpsUpdates", e.toString());
    }catch(SecurityException e){
       app.logError(CN + "startGpsUpdates", e.toString());
    }
    */
}

From source file:arc.noaa.weather.activities.MainActivity.java

void getCityByLocation() {
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Explanation not needed, since user requests this himself

        } else {//  ww  w  .  j a  v  a2 s  . co  m
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    MY_PERMISSIONS_ACCESS_FINE_LOCATION);
        }

    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.getting_location));
        progressDialog.setCancelable(false);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dialog_cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        try {
                            locationManager.removeUpdates(MainActivity.this);
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        }
                    }
                });
        progressDialog.show();
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        }
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }
    } else {
        showLocationSettingsDialog();
    }
}

From source file:com.nogago.android.tracks.services.TrackRecordingService.java

private void onLocationChangedAsync(Location location) {
    Log.d(TAG, "TrackRecordingService.onLocationChanged");

    try {/*from   w w  w.j ava 2s  .  c  om*/
        // Don't record if the service has been asked to pause recording:
        if (!isRecording) {
            Log.w(TAG, "Not recording because recording has been paused.");
            return;
        }

        // This should never happen, but just in case (we really don't want the
        // service to crash):
        if (location == null) {
            Log.w(TAG, "Location changed, but location is null.");
            return;
        }

        // Don't record if the accuracy is too bad:
        if (location.getAccuracy() > minRequiredAccuracy) {
            Log.d(TAG, "Not recording. Bad accuracy.");
            return;
        }

        // At least one track must be available for appending points:
        recordingTrack = getRecordingTrack();
        if (recordingTrack == null) {
            Log.d(TAG, "Not recording. No track to append to available.");
            return;
        }

        // Update the idle time if needed.
        locationListenerPolicy.updateIdleTime(statsBuilder.getIdleTime());
        addLocationToStats(location);
        if (currentRecordingInterval != locationListenerPolicy.getDesiredPollingInterval()) {
            registerLocationListener();
        }

        Location lastRecordedLocation = providerUtils.getLastLocation();
        double distanceToLastRecorded = Double.POSITIVE_INFINITY;
        if (lastRecordedLocation != null) {
            distanceToLastRecorded = location.distanceTo(lastRecordedLocation);
        }
        double distanceToLast = Double.POSITIVE_INFINITY;
        if (lastLocation != null) {
            distanceToLast = location.distanceTo(lastLocation);
        }
        boolean hasSensorData = sensorManager != null && sensorManager.isEnabled()
                && sensorManager.getSensorDataSet() != null && sensorManager.isSensorDataSetValid();

        // If the user has been stationary for two recording just record the first
        // two and ignore the rest. This code will only have an effect if the
        // maxRecordingDistance = 0
        if (distanceToLast == 0 && !hasSensorData) {
            if (isMoving) {
                Log.d(TAG, "Found two identical locations.");
                isMoving = false;
                if (lastLocation != null && lastRecordedLocation != null
                        && !lastRecordedLocation.equals(lastLocation)) {
                    // Need to write the last location. This will happen when
                    // lastRecordedLocation.distance(lastLocation) <
                    // minRecordingDistance
                    if (!insertLocation(lastLocation, lastRecordedLocation, recordingTrackId)) {
                        return;
                    }
                }
            } else {
                Log.d(TAG, "Not recording. More than two identical locations.");
            }
        } else if (distanceToLastRecorded > minRecordingDistance || hasSensorData) {
            if (lastLocation != null && !isMoving) {
                // Last location was the last stationary location. Need to go back and
                // add it.
                if (!insertLocation(lastLocation, lastRecordedLocation, recordingTrackId)) {
                    return;
                }
                isMoving = true;
            }

            // If separation from last recorded point is too large insert a
            // separator to indicate end of a segment:
            boolean startNewSegment = lastRecordedLocation != null && lastRecordedLocation.getLatitude() < 90
                    && distanceToLastRecorded > maxRecordingDistance && recordingTrack.getStartId() >= 0;
            if (startNewSegment) {
                // Insert a separator point to indicate start of new track:
                Log.d(TAG, "Inserting a separator.");
                Location separator = new Location(LocationManager.GPS_PROVIDER);
                separator.setLongitude(0);
                separator.setLatitude(100);
                separator.setTime(lastRecordedLocation.getTime());
                providerUtils.insertTrackPoint(separator, recordingTrackId);
            }

            if (!insertLocation(location, lastRecordedLocation, recordingTrackId)) {
                return;
            }
        } else {
            Log.d(TAG,
                    String.format(Locale.US,
                            "Not recording. Distance to last recorded point (%f m) is less than %d m.",
                            distanceToLastRecorded, minRecordingDistance));
            // Return here so that the location is NOT recorded as the last location.
            return;
        }
    } catch (Error e) {
        // Probably important enough to rethrow.
        Log.e(TAG, "Error in onLocationChanged", e);
        throw e;
    } catch (RuntimeException e) {
        // Safe usually to trap exceptions.
        Log.e(TAG, "Trapping exception in onLocationChanged", e);
        throw e;
    }
    lastLocation = location;
}