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:com.temboo.example.FoursquareConnectedActivity.java

/**
 * onCreate is called by Android when the activity is first created.
 *///from   w  w w .  j  a  va  2  s .c om
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Initialize the UI with the "connected mode" layout (defined in /res/layout/foursquare_connected.xml)
    setContentView(R.layout.foursquare_connected);

    // Obtain a reference to the "current venue" textview
    currentVenueTextView = (TextView) findViewById(R.id.foursquareVenueField);

    // Initiate the Temboo session
    try {
        session = new MyTemboo(TEMBOO_APPKEY_NAME, TEMBOO_APPKEY);
    } catch (Exception e) {
        currentVenueTextView.setText("Uh-oh! Something has gone horribly wrong.");
        Log.e("TEMBOO", "Error starting Temboo session.", e);
    }

    // Debug: display the Fourquare Oauth token retrieved by FoursquareOauthActivity
    Toast.makeText(FoursquareConnectedActivity.this,
            "Successfully connected to Foursquare. Oauth token: " + FOURSQUARE_OAUTH_TOKEN, Toast.LENGTH_SHORT)
            .show();

    // Obtain a reference to the Android LocationManager, which is (surprisingly) responsible for managing GPS/location data
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // Get and store the last known location
    currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    // Register a listener with the Location Manager to receive location updates. Currently, this is configured
    // to request GPS updates every 3 minutes, with a minimum location-differential of 3 meters per update. 
    // See http://developer.android.com/reference/android/location/LocationManager.html
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 180000, 3, new LocationListener() {

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

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        // When the location changes, store the current location in the parent activity
        @Override
        public void onLocationChanged(Location location) {
            currentLocation = location;
        }
    });

    // Attach the "lookup location" button click handler
    Button lookupButton = (Button) findViewById(R.id.getVenue);
    lookupButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                getFoursquareVenueForCurrentLocation();
            } catch (Exception e) {
                Log.e("TEMBOO", "Error performing Foursquare venue lookup", e);
                Toast.makeText(FoursquareConnectedActivity.this,
                        "Error performing foursquare venue lookup! " + e.getMessage(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });

    // Attach the "Foursquare checkin" button click handler
    Button checkinButton = (Button) findViewById(R.id.doFoursquareCheckin);
    checkinButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                doFoursquareCheckin();
            } catch (Exception e) {
                Log.e("TEMBOO", "Error performing Foursquare checkin", e);
                Toast.makeText(FoursquareConnectedActivity.this,
                        "Error performing foursquare checkin! " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });
}

From source file:com.example.s_geomapsample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample_map);

    mLatitude = (TextView) findViewById(R.id.latitude);
    mAccuracy = (TextView) findViewById(R.id.accuracy);
    mLongitude = (TextView) findViewById(R.id.longitude);

    mProvider = (TextView) findViewById(R.id.t01);

    mHandler = new Handler();

    // mApp = (ApplicationClass) getApplication();
    // mApp.setOnNotifiedMessageListener(mNotifiedMessageListener);
    // mLocationManager = new LocationServiceManager(getApplication());

    upReceiver = new UpdateReceiver();
    intentFilter = new IntentFilter();
    intentFilter.addAction("UPDATE_ACTION");
    registerReceiver(upReceiver, intentFilter);

    upReceiver.registerHandler(updateHandler);

    // ?/*  w w w .j a  va2s  .c o  m*/
    Button setParamButton = (Button) findViewById(R.id.param);
    setParamButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mGeoFenceManager = new GeoFenceManager(MainActivity.this);
            HashMap<String, Object> defaultMap = new HashMap<String, Object>();
            {
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_CLIENTID, "JSZ3a03eb052f46|E7Tg6");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TMID, "t1000_1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_SECRET, "eNphiW-zYeDhnj37IL86bJeijmA");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TNTP, "1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TATP, "1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_NCURL,
                        "https://test-mlp.its-mo.com/mlp/v1_0/request/SearchNotifyConditionList.php");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_AIURL,
                        "https://test-mlp.its-mo.com/mlp/v1_0/request/SearchAreaInfoList.php");
                defaultMap.put("SAVE_INTERVAL", "2");
            }

            int result = mGeoFenceManager.setParams(defaultMap, 1);
            if (result == GeoFenceManager.SET_PARAMS_RESULT_CODE_SUCCESS) {
                Toast.makeText(MainActivity.this, "SET_PARAMS_RESULT_CODE_SUCCESS", Toast.LENGTH_LONG).show();
            } else if (result == GeoFenceManager.SET_PARAMS_RESULT_CODE_NO_REQUIRED) {
                Toast.makeText(MainActivity.this, "SET_PARAMS_RESULT_CODE_NO_REQUIRED", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Area
    Button updateButton = (Button) findViewById(R.id.update);
    updateButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            int updateAreaInfomation = mGeoFenceManager.updateAreaInfomation();
            Toast.makeText(MainActivity.this, "updateAreaInfomation = " + updateAreaInfomation,
                    Toast.LENGTH_LONG).show();
            // UpdateAreaAsync areaAsync = new
            // UpdateAreaAsync(MainActivity.this, mGeoFenceManager);
            // areaAsync.execute();
        }
    });
    // GPS???
    Button gpsButton = (Button) findViewById(R.id.gps_button);
    gpsButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationServiceManager locationServiceManager = new LocationServiceManager(MainActivity.this);
            locationServiceManager.startLocationService();
        }
    });

    // Google Play Services???????
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) {
        // Google Play Services ?????
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    } else {
        // Google Play Services ???
        // activity_main.xml?SupportMapFragment????
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // fragment?GoogleMap object?
        gMap = fm.getMap();

        // Google Map?MyLocation???
        gMap.setMyLocationEnabled(true);
        gMap.setIndoorEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        gMap.setTrafficEnabled(true);

        // ?LOCATION_SERVICE?LocationManager object?
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // retrieve provider?criteria object?
        Criteria criteria = new Criteria();

        // Best provider?????
        String provider = locationManager.getBestProvider(criteria, true);

        // ???
        Location location = locationManager.getLastKnownLocation(provider);

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

    }

}

From source file:com.platform.GeoLocationManager.java

public void startGeoSocket(Session sess) {
    session = sess;/*www. j ava 2s. c  om*/

    final MainActivity app = MainActivity.app;
    if (app == null)
        return;
    final LocationManager locationManager = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE);

    app.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (ActivityCompat.checkSelfPermission(app,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(app,
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                RuntimeException ex = new RuntimeException("startGeoSocket, can't happen");
                Log.e(TAG, "run: startGeoSocket, can't happen");
                FirebaseCrash.report(ex);
                return;
            }
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
                    socketLocationListener);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0,
                    socketLocationListener);

        }
    });
}

From source file:com.example.getneighborposition.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textview = (TextView) findViewById(R.id.tv_location);

    // Google Play Services???????
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) {
        // Google Play Services ?????
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();//from   w  w  w .  ja v  a  2 s.c  o  m

    } else {
        // Google Play Services ???
        // activity_main.xml?SupportMapFragment????
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // fragment?GoogleMap object?
        gMap = fm.getMap();

        // Google Map?MyLocation???
        gMap.setMyLocationEnabled(true);
        gMap.setIndoorEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        gMap.setTrafficEnabled(true);

        // ?LOCATION_SERVICE?LocationManager object?
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // retrieve provider?criteria object?
        Criteria criteria = new Criteria();

        // Best provider?????
        String provider = locationManager.getBestProvider(criteria, true);

        //provider??????????????
        if (provider != null) {
            Toast.makeText(this, provider + "???", Toast.LENGTH_LONG).show();

            Log.d("app", "the best provider is " + provider);
            // ???
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else { //GPS?????????
            Toast.makeText(this, "????????", Toast.LENGTH_LONG).show();
        }
    }

}

From source file:it.geosolutions.geocollect.android.core.mission.PendingMissionListActivity.java

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

    if (mIntentFilter == null) {
        mIntentFilter = new IntentFilter("android.location.PROVIDERS_CHANGED");
    }// ww  w .  ja va  2s . c  o  m

    if (mReceiver == null) {
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LocationManager locationManager = (LocationManager) PendingMissionListActivity.this
                        .getSystemService(Context.LOCATION_SERVICE);
                if (locationManager != null) {
                    locationManager.requestLocationUpdates(getProviderName(), LOCATION_MINTIME,
                            LOCATION_MINDISTANCE, PendingMissionListActivity.this);
                }
            }
        };
    }

    registerReceiver(mReceiver, mIntentFilter);

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager != null) {
        locationManager.requestLocationUpdates(getProviderName(), LOCATION_MINTIME, LOCATION_MINDISTANCE, this);
    }

    if (shouldStartMap) {
        launchFullMap();
    }
}

From source file:com.njlabs.amrita.aid.about.Amrita.java

public void directions_cbe(View view) {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;// w w  w  . j  a  v  a2  s .  c  o  m
    }

    LocationListener loc_listener = new LocationListener() {
        public void onLocationChanged(Location l) {
        }

        public void onProviderEnabled(String p) {
        }

        public void onProviderDisabled(String p) {
        }

        public void onStatusChanged(String p, int status, Bundle extras) {
        }
    };
    locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    double lat;
    double lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
    Uri uri = Uri.parse(
            "http://maps.google.com/maps?f=d&saddr=" + lat + "," + lon + "&daddr=10.900539,76.902806&hl=en");
    Intent it = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(it);

}

From source file:com.cs528.style.style.weather.WeatherActivity.java

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

        } else {//from   w  ww . j  a  va  2 s  .  c o  m
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    MY_PERMISSIONS_ACCESS_FINE_LOCATION);
        }

    } else {
        progressDialog.setMessage(getString(R.string.getting_location));
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    }
}

From source file:com.ibm.mf.geofence.demo.MapsActivity.java

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly installed) and the map has not already been instantiated.
 *///from  ww  w . j a va2  s.c  om
void setUpMapIfNeeded() {
    if (googleMap == null) {
        googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        log.debug("setUpMapIfNeeded() : googleMap = " + googleMap);
        if (googleMap != null) {
            LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            try {
                if (currentLocation == null)
                    currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            } catch (SecurityException e) {
                log.debug("missing permission to request get last location from NETWORK_PROVIDER");
            }
            initGeofences();
            // receive updates for th ecurrent location
            try {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10f,
                        new android.location.LocationListener() {
                            @Override
                            public void onLocationChanged(Location location) {
                                currentLocation = location;
                                refreshCurrentLocation();
                            }

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

                            @Override
                            public void onProviderEnabled(String provider) {
                            }

                            @Override
                            public void onProviderDisabled(String provider) {
                            }
                        });
            } catch (SecurityException e) {
                log.debug("missing permission to request locations from NETWORK_PROVIDER");
            }
            // set the map center and zoom level/bounds once it is loaded
            googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
                @Override
                public void onMapLoaded() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            List<MFGeofence> fences = geofenceHolder.getFences();
                            LatLng latlng = currentLocation != null
                                    ? new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude())
                                    : googleMap.getCameraPosition().target;
                            Map<String, Object> map = (fences != null) && !fences.isEmpty()
                                    ? DemoUtils.computeBounds(fences, latlng)
                                    : DemoUtils.computeBounds(latlng, 0.0005, 0.0005);
                            log.debug("setUpMapIfNeeded() : bounds map = " + map + ", fences = " + fences);
                            LatLngBounds bounds = (LatLngBounds) map.get("bounds");
                            LatLng loc = (LatLng) map.get("center");
                            if (currentZoom >= 0f) {
                                log.debug("setUpMapIfNeeded() setting zoom");
                                googleMap.moveCamera(CameraUpdateFactory.zoomTo(currentZoom));
                            } else {
                                log.debug("setUpMapIfNeeded() setting bounds");
                                googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
                            }
                            refreshCurrentLocation(loc.latitude, loc.longitude);
                        }
                    });
                }
            });
            // respond to taps on the fences labels
            googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    if (mapMode != MODE_EDIT) {
                        GeofenceInfo info = getGeofenceInfoForMarker(marker);
                        log.debug(String.format("onMarkerClick(marker=%s) info=%s", marker, info));
                        EditGeofenceDialog dialog = new EditGeofenceDialog();
                        dialog.customInit(MapsActivity.this, EditGeofenceDialog.MODE_UPDATE_DELETE, info);
                        dialog.show(getFragmentManager(), "geofences");
                    }
                    return true;
                }
            });
        }
    }
}

From source file:com.lcl.thumbweather.MainActivity.java

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

        } else {/*  ww  w  .j a  va  2s . c  o m*/
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    MY_PERMISSIONS_ACCESS_FINE_LOCATION);
        }

    } else {
        progressDialog.setMessage(getString(R.string.getting_location));
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
}

From source file:com.RSMSA.policeApp.OffenceReportForm.java

/**
 * Start listening and recording locations
 *//*from w w  w. j av a2 s  .com*/
public void startRecording() {
    gpsTimer.cancel();
    gpsTimer = new Timer();
    long checkInterval = 60 * 1000;
    long minDistance = 1000;
    // receive updates
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    for (String s : locationManager.getAllProviders()) {
        locationManager.requestLocationUpdates(s, checkInterval, minDistance, 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 this is a gps location, we can use it
                if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    doLocationUpdate(location, true);
                }
            }
        });
    }
    // start the gps receiver thread
    gpsTimer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            Location location = getBestLocation();
            doLocationUpdate(location, false);
        }
    }, 0, checkInterval);
}