List of usage examples for android.location LocationManager getLastKnownLocation
@RequiresPermission(anyOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION })
public Location getLastKnownLocation(String provider)
From source file:com.nextgis.mobile.forms.CompassFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // reference to vibrator service vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE); // vibrate or not? SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); vibrationOn = prefs.getBoolean("compass_vibration", true); if (mCurrentLocation == null) { LocationManager locationManager = (LocationManager) getActivity() .getSystemService(Context.LOCATION_SERVICE); mCurrentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (mCurrentLocation == null) { mCurrentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); }/* ww w .j a v a 2 s . c o m*/ } mDeclination = 0; if (mCurrentLocation != null) { mDeclination = getDeclination(mCurrentLocation, System.currentTimeMillis()); } sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL); getActivity().registerReceiver(compassBroadcastReceiver, new IntentFilter(ACTION_COMPASS_UPDATES)); Log.d(TAG, "CompassActivity: onCreate"); }
From source file:com.example.b1013029.myapplication.MapsActivity.java
private void setMyLocation() { LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); Location lastLocate = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (lastLocate != null) { LatLng position = new LatLng(lastLocate.getLatitude(), lastLocate.getLongitude()); this.gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, gMap.getCameraPosition().zoom)); } else {/* ww w.ja va 2 s . co m*/ Toast.makeText(this, "????????", Toast.LENGTH_SHORT).show(); } }
From source file:heartware.com.heartware_master.FB_PickerActivity.java
@Override protected void onStart() { super.onStart(); if (FRIEND_PICKER.equals(getIntent().getData())) { try {//w w w . ja v a 2 s . c om friendPickerFragment.loadData(false); } catch (Exception ex) { onError(ex); } } else if (PLACE_PICKER.equals(getIntent().getData())) { try { Location location = null; Criteria criteria = new Criteria(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String bestProvider = locationManager.getBestProvider(criteria, false); if (bestProvider != null) { location = locationManager.getLastKnownLocation(bestProvider); if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { boolean updateLocation = true; Location prevLocation = placePickerFragment.getLocation(); if (prevLocation != null) { updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD; } if (updateLocation) { placePickerFragment.setLocation(location); placePickerFragment.loadData(true); } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD, locationListener, Looper.getMainLooper()); } } if (location == null) { String model = Build.MODEL; if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) { // this may be the emulator, pretend we're in an exotic place location = TEMPE_AZ_LOCATION; } location = TEMPE_AZ_LOCATION; // @TODO HARDCODED location } if (location != null) { location = TEMPE_AZ_LOCATION; placePickerFragment.setLocation(location); placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS); placePickerFragment.setSearchText(SEARCH_TEXT); placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT); placePickerFragment.loadData(false); } else { onError(getResources().getString(R.string.no_location_error), true); } } catch (Exception ex) { onError(ex); } } }
From source file:ly.apps.android.rest.client.example.activities.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textViewDescription = (TextView) findViewById(R.id.textview_description); textViewTemp = (TextView) findViewById(R.id.textview_temp); imageViewIcon = (ImageView) findViewById(R.id.imageview_icon); textViewWind = (TextView) findViewById(R.id.textview_wind_response); textViewHumidity = (TextView) findViewById(R.id.textview_humidity_response); textViewTempMax = (TextView) findViewById(R.id.textview_tempmax_response); textViewTempMin = (TextView) findViewById(R.id.textview_tempmin_response); textViewCity = (TextView) findViewById(R.id.textview_city); contentProgressBar = (LinearLayout) findViewById(R.id.content_progressbar); linearLayoutContent = (LinearLayout) findViewById(R.id.content); contentBottom = (LinearLayout) findViewById(R.id.bottom_content); descriptionTempContent = (LinearLayout) findViewById(R.id.description_temp_content); RestClient client = RestClientFactory.defaultClient(getApplicationContext()); api = RestServiceFactory.getService(getString(R.string.base_url), OpenWeatherAPI.class, client); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); checkImmersiveMode();/*ww w. j av a2 s . c o m*/ if ((location != null) && checkConnection(getApplicationContext())) { setLocation(location); } else { failMessage(); } }
From source file:com.keysolutions.meteorparties.PartyMapFragment.java
/** * Gets current location using Android's location provider * so you can zoom the map to it/*from w ww. j a va 2 s . co m*/ * @return last known Location */ @SuppressWarnings("unused") private Location getCurrentLocation() { Criteria criteria = new Criteria(); LocationManager locMan = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); String towers = locMan.getBestProvider(criteria, false); Location location = locMan.getLastKnownLocation(towers); return location; }
From source file:ca.ualberta.cs.cmput301w15t04team04project.MainActivity.java
/** * Called to do initial creation of a fragment.<br> * This is called after onAttach(Activity) and before * onCreateView(LayoutInflater, ViewGroup, Bundle).<br> * Note that this can be called while the fragment's activity is still in * the process of being created.<br> * As such, you can not rely on things like the activity's content view * hierarchy being initialized at this point.<br> * If you want to do work once the activity itself is created, see * onActivityCreated(Bundle).<br>//from w w w. j a v a 2s .c om * * @param savedInstanceState * If the fragment is being re-created from a previous saved * state, this is the state. */ /* * (non-Javadoc) * * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // searchClaim.setVisible(true); setContentView(R.layout.activity_main); checker = new NetworkAvailabliltyCheck(getApplicationContext()); user = SignInManager.loadFromFile(this); actionBar = getActionBar(); actionBar.setTitle("My Local Claims"); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (checker.getNetworkAvailable()) { Toast.makeText(this, "net", Toast.LENGTH_SHORT).show(); ClaimList claimList = MyLocalClaimListManager.loadClaimList(getApplicationContext(), user.getName()); localController = new MyLocalClaimListController(claimList); localController.upload(getApplicationContext()); } /* * if (location != null){ user.setHomelocation(location); TextView tv = * (TextView) findViewById(R.id.gpsHomeLocationTextView); * tv.setText("Lat: " + location.getLatitude() + "\nLong: " + * location.getLongitude()); } */ lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, listener); initialisePaging(); }
From source file:ca.ualberta.cs.cmput301w15t04team04project.MainActivity.java
/** * Will be called when user clicked add Location button, it will pop a * dialog and let user choose the method of location which go to the * osmMainAcitivity// www. ja v a 2s. co m * * @param v * View passed to the activity to check which button was pressed. */ public void goToMapAction(View v) { AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this); if (user.getHomelocation() != null) { adb.setMessage("Current Home Location is " + user.getHomelocation().getLatitude() + user.getHomelocation().getLongitude() + "\nChoose the HomeLocation Way"); } else { adb.setMessage("Choose the HomeLocation Way"); } adb.setNegativeButton("GPS", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); homeLocation = location; user.setHomelocation(location); } }); adb.setPositiveButton("Map", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(MainActivity.this, osmMainActivity.class); startActivity(intent); } }); adb.setCancelable(true); adb.show(); }
From source file:org.akvo.flow.ui.fragment.MapFragment.java
/** * Center the map in the given record's coordinates. If no record is provided, * the user's location will be used.// w w w. java 2s. c o m * @param record */ private void centerMap(SurveyedLocale record) { if (mMap == null) { return; // Not ready yet } LatLng position = null; if (record != null && record.getLatitude() != null && record.getLongitude() != null) { // Center the map in the data point position = new LatLng(record.getLatitude(), record.getLongitude()); } else { // When multiple points are shown, center the map in user's location LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); String provider = manager.getBestProvider(criteria, true); if (provider != null) { Location location = manager.getLastKnownLocation(provider); if (location != null) { position = new LatLng(location.getLatitude(), location.getLongitude()); } } } if (position != null) { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 10)); } }
From source file:com.example.demo_dv_fuse.MapScreen.java
/** * @see android.app.Activity#onCreate(android.os.Bundle) *//*from www.j a v a 2s. com*/ @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:es.uja.photofirma.android.CameraActivity.java
/** * Controla los accesos y retornos a las aplicaciones de caputura de fotografas y '@firma', se establece * para cada caso tanto la situacion de exito como la de fracaso. */// w w w. j av a 2 s . c o m @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Vuelta de @firma, el resultCode indica exito o fracaso, en cada caso se toman unas medidas diferentes if (requestCode == CameraActivity.APP_FIRMA_REQUEST_CODE && resultCode == CameraActivity.RESULT_ERROR) { logger.appendLog(402, "el usuario deniega el uso del certificado"); showErrorHeader(); } //Vuelta de @firma, la firma fue realizada con exito, se almacena la ruta al archivo if (requestCode == CameraActivity.APP_FIRMA_REQUEST_CODE && resultCode == RESULT_OK) { logger.appendLog(200, "@firma realiz la firma adecuadamente"); signedFileLocation = data.getExtras().getString("signedfilelocation"); showSuccessHeader(); } //Si la captura de la fotografa tuvo exito if (requestCode == CameraActivity.REQUEST_IMAGE_CAPTURE & resultCode == RESULT_OK) { logger.appendLog(101, "el usuario captura foto"); //Se obtienen los datos del servicio de localizacin geografica LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); // Aade los geoTags a la foto realizada anteriormente if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && location != null) { PhotoCapture.addExifData(photoLocation, location); logger.appendLog(102, "el usuario aade exif"); logger.appendLog(103, "gps data: " + location); } logger.appendLog(104, "buscando @firma"); //Se comprueba si est la app @firma Intent intent = getPackageManager().getLaunchIntentForPackage("es.gob.afirma"); if (intent == null) { //Si no se encuentra instalada se notifica al usuario logger.appendLog(400, "@firma no instalada"); showErrorHeader(); errorText.setText(getString(R.string.camera_activity_no_afirma_present)); } else { //Si se encuentra, entonces se abre para dar comienzo al proceso de firma logger.appendLog(201, "abriendo @firma"); Intent i = new Intent(APP_FIRMA_OPEN_ACTION); i.putExtra(CameraActivity.APP_FIRMA_EXTRA_FILE_PATH, photoLocation); startActivityForResult(i, APP_FIRMA_REQUEST_CODE); } } //Si la captura de fotos fue cancelada if (requestCode == CameraActivity.REQUEST_IMAGE_CAPTURE && resultCode == CameraActivity.RESULT_CANCELED) { showInfoHeader(); logger.appendLog(105, "cierra la app de photo sin captura"); } //Si la captura de fotos fue cancelada if (requestCode == CameraActivity.REQUEST_IMAGE_CAPTURE && resultCode == CameraActivity.RESULT_ERROR) { showInfoHeader(); logger.appendLog(403, "Se produjo un error en la app de Cmara"); } }