Example usage for android.location LocationManager requestLocationUpdates

List of usage examples for android.location LocationManager requestLocationUpdates

Introduction

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

Prototype

@UnsupportedAppUsage
    private void requestLocationUpdates(LocationRequest request, LocationListener listener, Looper looper,
            PendingIntent intent) 

Source Link

Usage

From source file:org.runnerup.gpstracker.GpsTracker.java

public void startLogging() {
    assert (state == State.INIT);
    wakelock(true);/*from ww w  . j ava  2  s  .co  m*/
    String frequency_ms = PreferenceManager.getDefaultSharedPreferences(this).getString("pref_pollInterval",
            "500");
    String frequency_meters = PreferenceManager.getDefaultSharedPreferences(this).getString("pref_pollDistance",
            "5");
    // TODO add preference
    mMinLiveLogDelayMillis = PreferenceManager.getDefaultSharedPreferences(this)
            .getInt("pref_min_livelog_delay_millis", (int) mMinLiveLogDelayMillis);

    LocationManager lm = (LocationManager) this.getSystemService(LOCATION_SERVICE);
    try {
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, Integer.valueOf(frequency_ms),
                Integer.valueOf(frequency_meters), this);
        state = State.LOGGING;
    } catch (Exception ex) {
        state = State.ERROR;
    }

    startHRMonitor();

    UploadManager u = new UploadManager(this);
    u.loadLiveLoggers(liveLoggers);
    u.close();
}

From source file:com.swetha.easypark.GoogleDirectionsActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mapdirections);
    StrictMode.setThreadPolicy(/*w w w . j a  va 2s  . c om*/
            new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
                    .penaltyLog().build());
    Log.i("GoogleDirectionsActivity", "Inside Oncreate");

    Intent theIntent = getIntent();
    tolat = theIntent.getDoubleExtra(GetParkingLots.LATITUDE, Constants.doubleDefaultValue);
    tolng = theIntent.getDoubleExtra(GetParkingLots.LONGITUDE, Constants.doubleDefaultValue);

    toPosition = new LatLng(tolat, tolng);

    Log.i("GoogleDirectionsActivity",
            "After Setting tolat, tolng, toPosition" + tolat + "\n" + tolng + "\n" + toPosition);

    md = new GetDirections();
    Log.i("GoogleDirectionsActivity", "After calling GetDirctions constructor");

    FragmentManager fm = getSupportFragmentManager();
    Log.i("GoogleDirectionsActivity", "After creating fragmentManager" + fm);
    SupportMapFragment supportMapfragment = ((SupportMapFragment) fm.findFragmentById(R.id.drivingdirections));

    Log.i("GoogleDirectionsActivity", "After creating SupportMapFragment" + supportMapfragment);
    mMap = supportMapfragment.getMap();
    Log.i("GoogleDirectionsActivity", "After getting map");

    mMap.setMyLocationEnabled(true);
    Log.i("GoogleDirectionsActivity", "After  setMyLocationEnabled");
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Log.i("GoogleDirectionsActivity", "After  locationManager");
    Criteria criteria = new Criteria();

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

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

        // Get the location from the given provider 
        location = locationManager.getLastKnownLocation(provider);

        locationManager.requestLocationUpdates(provider, 500, 1, GoogleDirectionsActivity.this);

        if (location != null) {

            fromlat = location.getLatitude();
            fromlng = location.getLongitude();
        }

        else {
            fromlat = GetParkingLots.latitude;
            fromlng = GetParkingLots.longitude;
        }

    } else {
        Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
        finish();
    }
    Log.e("GoogleDirectionsActivity", "After  setting location");
    fromPosition = new LatLng(fromlat, fromlng);
    LatLng coordinates = new LatLng(fromlat, fromlng);
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));

    mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
    mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));

    Document doc = md.getDocument(fromPosition, toPosition, Constants.MODE_DRIVING);
    String duration = md.getDurationText(doc);

    tv_duration = (TextView) findViewById(R.id.tv_time);
    tv_duration.setText("Estimated driving time:" + duration);

    ArrayList<LatLng> directionPoint = md.getDirection(doc);

    PolylineOptions rectLine = new PolylineOptions().width(6).color(Color.RED);

    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }

    mMap.addPolyline(rectLine);
}

From source file:com.dat255.ht13.grupp23.view.MapView.java

/**
 * Initiating the GoogleMap and all necessary items for the configuration
 * /*  www .  j a  v  a 2s .c om*/
 * @param fragmentActivity
 */
private void initiateMap(FragmentActivity fragmentActivity) {
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(fragmentActivity.getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are
        // not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, fragmentActivity, requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) fragmentActivity.getSupportFragmentManager()
                .findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service
        // LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) fragmentActivity
                .getSystemService(Context.LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }

}

From source file:net.jongrakko.zipsuri.activity.PostUploadActivity.java

@Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
    if (isChecked) {
        switch (buttonView.getId()) {
        case R.id.radioButtonAddressGPS:
            mEditTextAddress.setOnClickListener(null);
            this.mGoogleMap.setOnMapClickListener(this);
            this.mGoogleMap.setOnMyLocationButtonClickListener(this);

            if (ContextCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mGoogleMap.setMyLocationEnabled(true);
                LocationProvider lprovider;
                LocationManager lm = (LocationManager) getActivity()
                        .getSystemService(getActivity().LOCATION_SERVICE);
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
                lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
                String provider;//  ww  w  .j a v a2 s  . co m
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                criteria.setPowerRequirement(Criteria.POWER_HIGH);
                provider = lm.getBestProvider(criteria, true);

                if (provider == null || provider.equals("passive")) { // ? ?    ??
                    new AlertDialog.Builder(getActivity()).setTitle(" ??")
                            .setNeutralButton("??", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    buttonView.toggle();
                                    startActivityForResult(
                                            new Intent(
                                                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
                                            0);
                                }
                            }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    dialog.dismiss();
                                }
                            }).show();
                } else { //  ? ?   
                    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
                    Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (l != null) {
                        Log.e("hello??", "okok");
                    }
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                            MY_LOCATION_REQUEST_CODE);
                }
            }
            break;
        case R.id.radioButtonAddressSelf:
            this.mGoogleMap.setOnMapClickListener(null);
            mEditTextAddress.setOnClickListener(this);
            this.mGoogleMap.setOnMyLocationButtonClickListener(null);
            mGoogleMap.setMyLocationEnabled(false);
            mEditTextAddress.setOnClickListener(this);
            startActivityForResult(new Intent(getContext(), SearchAddressActivity.class), SEARCH_ADDRESS);
            break;
        }
    }
}

From source file:com.johan.vertretungsplan_2.SelectSchoolActivity.java

private void showListGeo() {
    final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE); // no GPS
    final String provider = locationManager.getBestProvider(criteria, true);

    if (provider == null) {
        Log.d("vertretungsplan", "provider==null");
        tvLocateString.setText(R.string.geolocate_disabled);
        status = Status.LIST;/* ww w  .j  a va2  s .  co m*/
        return;
    }
    locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            if (!visible)
                return;
            if (location != null) {
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                for (Schule school : schools) {
                    float[] result = new float[1];
                    Location.distanceBetween(lat, lon, school.getGeo()[0], school.getGeo()[1], result);
                    school.setDistance(result[0]);
                    Log.d("vertretungsplan", school.getName() + ": " + school.getDistance());
                }
                Collections.sort(schools, new DistanceSchoolComparator());
                lstSchools.setAdapter(new SchoolsAdapter(SelectSchoolActivity.this, schools, true));
            }
            tvLocateString.setText(R.string.alphabetic_list);
            ivLocationIcon.setImageResource(R.drawable.ic_action_view_as_list);
            status = Status.GEO;
        }
    });
}

From source file:com.zainsoft.ramzantimetable.QiblaActivity.java

private void registerForGPS() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);//from   w ww .  jav  a 2  s.  c  om
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);
    LocationManager locationManager = ((LocationManager) getSystemService(Context.LOCATION_SERVICE));
    String provider = locationManager.getBestProvider(criteria, true);

    if (provider != null) {
        locationManager.requestLocationUpdates(provider, MIN_LOCATION_TIME, MIN_LOCATION_DISTANCE,
                qiblaManager);
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_LOCATION_TIME,
            MIN_LOCATION_DISTANCE, qiblaManager);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_LOCATION_TIME,
            MIN_LOCATION_DISTANCE, qiblaManager);
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location == null) {
        location = ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }
    if (location != null) {
        qiblaManager.onLocationChanged(location);
    }

}

From source file:com.facebook.react.modules.location.LocationModule.java

/**
 * Start listening for location updates. These will be emitted via the
 * {@link RCTDeviceEventEmitter} as {@code geolocationDidChange} events.
 *
 * @param options map containing optional arguments: highAccuracy (boolean)
 *///w ww.  j  a  va 2s .c o  m
@ReactMethod
public void startObserving(ReadableMap options) {
    if (LocationManager.GPS_PROVIDER.equals(mWatchedProvider)) {
        return;
    }
    LocationOptions locationOptions = LocationOptions.fromReactMap(options);

    try {
        LocationManager locationManager = (LocationManager) getReactApplicationContext()
                .getSystemService(Context.LOCATION_SERVICE);
        String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
        if (provider == null) {
            emitError(PositionError.POSITION_UNAVAILABLE, "No location provider available.");
            return;
        }
        if (!provider.equals(mWatchedProvider)) {
            locationManager.removeUpdates(mLocationListener);
            locationManager.requestLocationUpdates(provider, 1000, locationOptions.distanceFilter,
                    mLocationListener);
        }
        mWatchedProvider = provider;
    } catch (SecurityException e) {
        throwLocationPermissionMissing(e);
    }
}

From source file:com.refujiate.ui.MainMapaActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_ubicacion);
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();// w w  w . ja  va  2 s  .  c om

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        googleMap.moveCamera(
                CameraUpdateFactory.newLatLngZoom(new LatLng(-8.105972881341886, -79.028778076171880), 12));

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);
    }
    addMaker(0);
    Intent svc = new Intent(this, RefugiateService.class);
    startService(svc);
}

From source file:it.unipr.informatica.autobusparma.MappaFragment.java

public Location getLocation(long MIN_DISTANCE, long MIN_TIME) {
    Location location = null;/*from w w w.  ja v  a 2s  .c o  m*/
    try {
        LocationManager locationManager = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
        // getting GPS status e network
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE,
                        this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE,
                            this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                }
            }
        }

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

    return location;
}

From source file:uk.ac.horizon.ug.exploding.client.LocationUtils.java

public static void registerOnThread(Context context, LocationListener locationCallback, Listener listener) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getAllProviders();
    Log.i(TAG, "Found " + providers.size() + " location providers");
    for (String provider : providers) {
        if (locationManager.isProviderEnabled(provider)) {
            Log.i(TAG, "Provider " + provider + " enabled");
        } else {//from   ww  w  .j  a v a  2s .com
            Log.i(TAG, "Provider " + provider + " disabled");
        }
    }
    for (int pi = 0; pi < PROVIDERS.length; pi++) {
        String provider = PROVIDERS[pi];
        if (locationManager.isProviderEnabled(provider)) {
            Log.i(TAG, "Registering with provider " + provider);
            Location loc = locationManager.getLastKnownLocation(provider);
            if (loc != null) {
                Log.i(TAG,
                        "Last Location, provider=" + loc.getProvider() + ", lat=" + loc.getLatitude()
                                + ", long=" + loc.getLongitude() + ", bearing="
                                + (loc.hasBearing() ? "" + loc.getBearing() : "NA") + ", speed="
                                + (loc.hasSpeed() ? "" + loc.getSpeed() : "NA") + ", accuracy="
                                + (loc.hasAccuracy() ? "" + loc.getAccuracy() : "NA") + ", alt="
                                + (loc.hasAltitude() ? "" + loc.getAltitude() : "NA"));

                ZoneService.updateLocation(context, loc);

            }
            //if (!"passive".equals(provider))
            if (locationCallback != null)
                locationManager.requestLocationUpdates(provider, 0/*minTime*/, 0/*minDistance*/,
                        locationCallback);
        } else
            Log.e(TAG, "Required provider " + provider + " not enabled!");
    }
    if (listener != null)
        locationManager.addGpsStatusListener(listener);
}