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.ohmage.triggers.types.location.LocTrigService.java

private void startGPS() {
    if (mGPSStarted) {
        return;/* w  w  w. j av a2 s .  c  om*/
    }

    if (LocTrigConfig.useMotionDetection) {
        stopMotionDetection();
    }

    //Get a wake lock for this duty cycle
    acquireWakeLock();

    mNSamples = 0;
    mPrevSpeed = mCurrSpeed;

    Log.i(DEBUG_TAG, "LocTrigService: Turning on location updates");

    LocationManager locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
    locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    //Use network location as well
    if (LocTrigConfig.useNetworkLocation) {

        if (mWifiLock != null) {
            if (!mWifiLock.isHeld()) {
                mWifiLock.acquire();
            }
        }

        locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    }

    cancelSamplingAlarm(ACTION_ALRM_GPS_SAMPLE);
    //Set GPS timeout
    setSamplingAlarm(ACTION_ALRM_GPS_TIMEOUT, GPS_TIMEOUT, 0);

    mGPSStarted = true;
}

From source file:org.ohmage.reminders.types.location.LocTrigService.java

private void startGPS() {
    if (mGPSStarted) {
        return;/*from ww  w .  j av a  2s.c o m*/
    }

    if (LocTrigConfig.useMotionDetection) {
        stopMotionDetection();
    }

    //Get a wake lock for this duty cycle
    acquireWakeLock();

    mNSamples = 0;
    mPrevSpeed = mCurrSpeed;

    Log.v(TAG, "LocTrigService: Turning on location updates");

    LocationManager locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
    List<String> providers = locMan.getAllProviders();

    if (providers.contains(LocationManager.GPS_PROVIDER))
        locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    //Use network location as well
    if (LocTrigConfig.useNetworkLocation) {

        if (mWifiLock != null) {
            if (!mWifiLock.isHeld()) {
                mWifiLock.acquire();
            }
        }

        if (providers.contains(LocationManager.NETWORK_PROVIDER))
            locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    }

    cancelSamplingAlarm(ACTION_ALRM_GPS_SAMPLE);
    //Set GPS timeout
    setSamplingAlarm(ACTION_ALRM_GPS_TIMEOUT, GPS_TIMEOUT, 0);

    mGPSStarted = true;
}

From source file:org.odk.collect.android.activities.GeoTraceOsmMapActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.geotrace_osm_layout);
    setTitle(getString(R.string.geotrace_title)); // Setting title of the action

    mapView = (MapView) findViewById(R.id.geotrace_mapview);
    helper = new MapHelper(this, mapView, GeoTraceOsmMapActivity.this);
    mapView.setMultiTouchControls(true);
    mapView.setBuiltInZoomControls(true);
    mapView.getController().setZoom(zoomLevel);
    myLocationOverlay = new MyLocationNewOverlay(mapView);

    inflater = this.getLayoutInflater();
    traceSettingsView = inflater.inflate(R.layout.geotrace_dialog, null);
    polygonPolylineView = inflater.inflate(R.layout.polygon_polyline_dialog, null);
    timeDelay = (Spinner) traceSettingsView.findViewById(R.id.trace_delay);
    timeDelay.setSelection(3);/*from   www .  j a v a  2 s .co m*/
    timeUnits = (Spinner) traceSettingsView.findViewById(R.id.trace_scale);
    layersButton = (ImageButton) findViewById(R.id.layers);
    layersButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            helper.showLayersDialog(GeoTraceOsmMapActivity.this);

        }
    });

    locationButton = (ImageButton) findViewById(R.id.show_location);
    locationButton.setEnabled(false);
    locationButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            reset_trace_settings();
            showZoomDialog();
        }

    });

    clearButton = (ImageButton) findViewById(R.id.clear);
    clearButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showClearDialog();

        }

    });

    ImageButton saveButton = (ImageButton) findViewById(R.id.geotrace_save);
    saveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (mapMarkers.size() != 0) {
                alertDialog.show();
            } else {
                saveGeoTrace();
            }
        }
    });
    if (mapMarkers == null || mapMarkers.size() == 0) {
        clearButton.setEnabled(false);
    }
    manualCaptureButton = (Button) findViewById(R.id.manual_button);
    manualCaptureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addLocationMarker();
        }
    });
    pauseButton = (ImageButton) findViewById(R.id.pause);
    playButton = (ImageButton) findViewById(R.id.play);
    playButton.setEnabled(false);
    beenPaused = false;
    traceMode = 1;

    playButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (!playCheck) {
                if (!beenPaused) {
                    alert.show();
                } else {
                    RadioGroup rb = (RadioGroup) traceSettingsView.findViewById(R.id.radio_group);
                    int radioButtonID = rb.getCheckedRadioButtonId();
                    View radioButton = rb.findViewById(radioButtonID);
                    traceMode = rb.indexOfChild(radioButton);
                    if (traceMode == 0) {
                        setupManualMode();
                    } else if (traceMode == 1) {
                        setupAutomaticMode();
                    } else {
                        reset_trace_settings();
                    }
                }
                playCheck = true;
            } else {
                playCheck = false;
                startGeoTrace();
            }
        }
    });

    pauseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            playButton.setVisibility(View.VISIBLE);
            if (mapMarkers != null && mapMarkers.size() > 0) {
                clearButton.setEnabled(true);
            }
            pauseButton.setVisibility(View.GONE);
            manualCaptureButton.setVisibility(View.GONE);
            playCheck = true;
            modeActive = false;
            myLocationOverlay.disableFollowLocation();

            try {
                schedulerHandler.cancel(true);
            } catch (Exception e) {
                // Do nothing
            }
        }
    });

    overlayMapLayerListener();
    buildDialogs();
    Intent intent = getIntent();
    if (intent != null && intent.getExtras() != null) {
        if (intent.hasExtra(GeoTraceWidget.TRACE_LOCATION)) {
            String s = intent.getStringExtra(GeoTraceWidget.TRACE_LOCATION);
            playButton.setEnabled(false);
            clearButton.setEnabled(true);
            overlayIntentTrace(s);
            locationButton.setEnabled(true);
            //zoomToCentroid();
            zoomToBounds();

        }
    } else {
        myLocationOverlay.runOnFirstFix(centerAroundFix);
    }

    Button polygonSaveButton = (Button) polygonPolylineView.findViewById(R.id.polygon_save);
    polygonSaveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mapMarkers.size() > 2) {
                createPolygon();
                alertDialog.dismiss();
                saveGeoTrace();
            } else {
                alertDialog.dismiss();
                showPolygonErrorDialog();
            }

        }
    });
    Button polylineSaveButton = (Button) polygonPolylineView.findViewById(R.id.polyline_save);
    polylineSaveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            alertDialog.dismiss();
            saveGeoTrace();

        }
    });

    zoomDialogView = getLayoutInflater().inflate(R.layout.geoshape_zoom_dialog, null);

    zoomLocationButton = (Button) zoomDialogView.findViewById(R.id.zoom_location);
    zoomLocationButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            zoomToMyLocation();
            mapView.invalidate();
            zoomDialog.dismiss();
        }
    });

    zoomPointButton = (Button) zoomDialogView.findViewById(R.id.zoom_shape);
    zoomPointButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //zoomToCentroid();
            zoomToBounds();
            mapView.invalidate();
            zoomDialog.dismiss();
        }
    });

    mapView.invalidate();
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getProviders(true);
    for (String provider : providers) {
        if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
            locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            gpsOn = true;
        }
        if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
            locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            networkOn = true;
        }
    }
    if (gpsOn) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
    if (networkOn) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    }
}

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

private void startLocationUpdate() {
    if (updatingLocation) {
        return;//from w  w w  .ja  v  a  2 s. c  om
    }
    updatingLocation = true;
    LocationManager locationManager = (LocationManager) ApplicationLoader.applicationContext
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, gpsLocationListener);
    } catch (Exception e) {
        FileLog.e(e);
    }
    try {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 0, networkLocationListener);
    } catch (Exception e) {
        FileLog.e(e);
    }
}

From source file:org.akvo.rsr.up.UpdateEditorActivity.java

/**
 * When the user clicks the "Get Location" button, start listening for
 * location updates/*w  w w  . ja v a 2  s. c o  m*/
 */
public void onGetGPSClick(View v) {
    LocationManager locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (needUpdate) {//turn off
        needUpdate = false;
        btnGpsGeo.setText(R.string.btncaption_gps_position);
        locMgr.removeUpdates(this);
        searchingIndicator.setText("");
        accuracyField.setText("");
        gpsProgress.setVisibility(View.GONE); //hide in-progress wheel
    } else {//turn on
        if (locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            positionGroup.setVisibility(View.VISIBLE);
            accuracyField.setText("?");
            accuracyField.setTextColor(Color.WHITE);
            latField.setText("");
            lonField.setText("");
            eleField.setText("");
            btnGpsGeo.setText(R.string.btncaption_gps_cancel);
            gpsProgress.setVisibility(View.VISIBLE); //Hide progress
            needUpdate = true;
            searchingIndicator.setText(R.string.label_gps_searching);
            lastAccuracy = UNKNOWN_ACCURACY;
            locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        } else {
            // we can't turn GPS on directly, the best we can do is launch the
            // settings page
            DialogUtil.showGPSDialog(this);
        }
    }

}

From source file:tv.piratemedia.flightcontroller.BluetoothComputerFragment.java

public void setupGPS() {
    LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            currentLat = location.getLatitude();
            currentLong = location.getLongitude();
            JSONObject msg = new JSONObject();
            try {
                msg.put("action", "location_update");
                msg.put("long", currentLong);
                msg.put("lat", currentLat);
            } catch (JSONException e) {
                e.printStackTrace();//from   w w  w .j  a  v  a2 s  .c om
            }
            sendTextMessage(msg.toString());
            Log.d("location", currentLat + " x " + currentLong);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

From source file:com.example.devesh.Coride.DriverRegistration.java

@TargetApi(Build.VERSION_CODES.M)
public void sendData(View view) throws MalformedURLException {
    Log.e("TEST LOG", "Entered the loop");
    Toast.makeText(this, "coride", Toast.LENGTH_SHORT).show();
    Master master = new Master();
    String url_string = master.url + "driverdata";
    EditText n_edittext;/*from   ww w .jav  a2  s  .co  m*/
    EditText mob_edittext;
    EditText confrm_edittext;
    EditText age_edittext;
    EditText lnumber;
    EditText pnumber;
    EditText vnumber;
    EditText mnumber;
    EditText capacity;
    String name;
    String mobile;
    String conpassword;
    String password;
    String address;
    String email;
    String slnumber;
    String spnumber;
    String svnumber;
    String smnumber;
    String scapacity;
    int count = 0;
    n_edittext = (EditText) findViewById(R.id.name);
    mob_edittext = (EditText) findViewById(R.id.mobileno);
    confrm_edittext = (EditText) findViewById(R.id.confirmpassword);
    mPasswordView = (EditText) findViewById(R.id.password);
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
    age_edittext = (EditText) findViewById(R.id.address);
    lnumber = (EditText) findViewById(R.id.lnumber);
    pnumber = (EditText) findViewById(R.id.pnumber);
    vnumber = (EditText) findViewById(R.id.vnumber);
    mnumber = (EditText) findViewById(R.id.mnumber);
    capacity = (EditText) findViewById(R.id.capacity);
    name = n_edittext.getText().toString();
    mobile = mob_edittext.getText().toString();
    master.mobile1 = mobile;
    password = mPasswordView.getText().toString();
    conpassword = confrm_edittext.getText().toString();
    address = age_edittext.getText().toString();
    email = mEmailView.getText().toString();
    slnumber = lnumber.getText().toString();
    spnumber = pnumber.getText().toString();
    svnumber = vnumber.getText().toString();
    smnumber = mnumber.getText().toString();
    ;
    scapacity = capacity.getText().toString();

    regId = registerGCM();
    System.out.println(regId);
    //        String reg=regId.toString();
    count = validate(name, email, mobile, password, conpassword, address);
    if (count == 0) {
        count = email_validation(mEmailView, getBaseContext());
    }
    if (count == 0) {
        count = password_matcher(password, conpassword);
    }

    if (count == 0) {

        String json = "[{name:\"" + name + "\"},{mobile:\"" + mobile + "\"},{password:\"" + password
                + "\"},{email:\"" + email + "\"},{address:\"" + address + "\"},{license:\"" + slnumber
                + "\"},{pan:\"" + spnumber + "\"},{vehicle:\"" + svnumber + "\"},{model:\"" + smnumber
                + "\"},{capacity:\"" + scapacity + "\"},{regid:\"" + regId + "\"}]";
        // snd.addNameValuePair("name", name);
        //snd.addNameValuePair("mobile", mobile);
        //snd.addNameValuePair("password", password);
        // snd.addNameValuePair("email",email);
        //snd.addNameValuePair("age", age);
        SendDataTask snd = new SendDataTask(json); //Go to sendData class fromhere
        URL url = new URL(url_string);
        snd.execute(url);

    }

    System.out.println("i am hear");
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER)
            || locationManager.isProviderEnabled(locationManager.GPS_PROVIDER)) {
        Log.e("Coride", "Provider enable");
        callLocationService();
    } else {
        Log.e("Coride", "provider disabled");
        showSettingsAlert("NETWORK_PROVIDER");

    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

            callLocationService();
        }

        @Override
        public void onProviderDisabled(String s) {
            showSettingsAlert("NETWORK_PROVIDER");
        }
    };
    //   dialog.cancel();

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 123);
        return;

    }
    locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 0, 0, locationListener);

}

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.
 */// w  w  w.  ja  va 2 s .  c o  m
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:com.example.demo_dv_fuse.MapScreen.java

/**
 * @see android.app.Activity#onCreate(android.os.Bundle)
 *//*from w w w. j a va  2  s. co  m*/
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_screen);
    this.map = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapView)).getMap();
    this.map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    if (status == ConnectionResult.SUCCESS) { // Google Play Services is available
        // Enabling MyLocation Layer of Google Map
        this.map.setMyLocationEnabled(true);

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

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

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

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

        if (location != null) {
            onLocationChanged(location);
            //            } else {
            //                final String coordinates[] = {"1.352566007", "103.78921587"};
            //                final double lat = Double.parseDouble(coordinates[0]);
            //                final double lng = Double.parseDouble(coordinates[1]);
            //
            //                // Creating a LatLng object for the current location
            //                LatLng latLng = new LatLng(lat, lng);
            //
            //                // Showing the current location in Google Map
            //                this.map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            //                this.map.animateCamera(CameraUpdateFactory.zoomTo(15));
        }
        boolean enabledGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean enabledWiFi = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        // Check if enabled and if not send user to the GSP settings
        // Better solution would be to display a dialog and suggesting to 
        // go to the settings
        if (!enabledGPS || !enabledWiFi) {
            Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);
    } else { // Google Play Services are not available
        final int requestCode = 10;
        final Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();
    }
}

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.  ja  v a2s.  c  o 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;
}