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:jp.co.tweetmap.Fragment0.java
/** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa.//w w w . j av a 2s. co m * <p/> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { if (LogUtil.isDebug()) Log.e(TAG, "### mapInit() ###"); // LocationManager LocationManager locationManager = (LocationManager) this.getActivity().getApplicationContext() .getSystemService(Context.LOCATION_SERVICE); double latitude = MapUtil.TOKYO_STATION_LATITUDE; double longitude = MapUtil.TOKYO_STATION_LONGITUDE; if (null != locationManager) { String bestProv = locationManager.getBestProvider(new Criteria(), true); // Get location information from GPS Location myLocate = locationManager.getLastKnownLocation(bestProv); if (null == myLocate) { myLocate = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (null == myLocate) { myLocate = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } if (null != myLocate) { latitude = myLocate.getLatitude(); longitude = myLocate.getLongitude(); } } CameraPosition camerapos = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(15.0f) .build(); // Move camera position mMap.moveCamera(CameraUpdateFactory.newCameraPosition(camerapos)); // Set current position mCenterPosition = camerapos; getNearestStation(); }
From source file:com.eutectoid.dosomething.PickerActivity.java
@Override protected void onStart() { super.onStart(); if (FRIEND_PICKER.equals(getIntent().getData())) { try {/*w w w . jav a 2 s . c o m*/ 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); // API 23: we have to check if ACCESS_FINE_LOCATION and/or ACCESS_COARSE_LOCATION permission are granted if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 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) { placePickerFragment.setLocation(location); placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS); placePickerFragment.setSearchText(SEARCH_TEXT); placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT); placePickerFragment.loadData(false); } } catch (Exception ex) { onError(ex); } } }
From source file:hr.foicore.varazdinlandmarksdemo.POIMapActivity.java
public boolean drawUserDestRoute(LatLng destination) { gmm.handleMapWarningMessages(POIMapActivity.this, tvMapMessage); if (!gmm.myLocationEnabled || !gmm.internetEnabled) { tvMapMessage.setBackgroundColor(POIMapActivity.this.getResources().getColor(R.color.red_transparent)); miDirections.setIcon(R.drawable.ic_action_directions); mActionDirections = 0;//from w ww . j a va 2 s . c o m tvMapDirectionsInfo.setVisibility(View.INVISIBLE); } else { if (gmm.googleMap.getMyLocation() != null) { userLocation = new LatLng(gmm.googleMap.getMyLocation().getLatitude(), gmm.googleMap.getMyLocation().getLongitude()); } else { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = service.getBestProvider(criteria, false); Location location = service.getLastKnownLocation(provider); if (location != null) { userLocation = new LatLng(location.getLatitude(), location.getLongitude()); } else { Toast.makeText(POIMapActivity.this, POIMapActivity.this.getResources().getString(R.string.my_location_problem), Toast.LENGTH_LONG).show(); return false; } } new connectAsyncTask(gmm.makeURL(userLocation.latitude, userLocation.longitude, destination.latitude, destination.longitude)).execute(); } return true; }
From source file:org.navitproject.navit.NavitDownloadSelectMapActivity.java
private void updateMapsForLocation(NavitMapDownloader.osm_map_values[] osm_maps) { Location currentLocation = NavitVehicle.lastLocation; if (maps_current_position_childs.size() == 0 || (currentLocation != null && !currentLocationKnown)) { if (currentLocation == null) { LocationManager mapLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> providers = mapLocationManager.getProviders(true); long lastUpdate; long bestUpdateTime = -1; for (String provider : providers) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; }//from www . ja v a 2 s .c om Location lastKnownLocation = mapLocationManager.getLastKnownLocation(provider); if (lastKnownLocation != null) { lastUpdate = lastKnownLocation.getTime(); if (lastUpdate > bestUpdateTime) { currentLocation = lastKnownLocation; bestUpdateTime = lastUpdate; } } } } else { currentLocationKnown = true; } if (currentLocation != null) { // if this map contains data to our current position, add it to // the MapsOfCurrentLocation-list for (int currentMapIndex = 0; currentMapIndex < osm_maps.length; currentMapIndex++) { if (osm_maps[currentMapIndex].isInMap(currentLocation)) { HashMap<String, String> currentPositionMapChild = new HashMap<String, String>(); currentPositionMapChild.put("map_name", osm_maps[currentMapIndex].map_name + " " + (osm_maps[currentMapIndex].est_size_bytes / 1024 / 1024) + "MB"); currentPositionMapChild.put("map_index", String.valueOf(currentMapIndex)); maps_current_position_childs.add(currentPositionMapChild); } } } } }
From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java
/********************************* * //from www . j a va2 s .c o m * Constructor * @param context * *********************************/ public LastFmEventImporter(Context context) { this.context = context; Log.i("LASTFMEVENT", "creating-------------------------"); /* * Check for Internet Connection (Through whichever interface) */ ConnectivityManager connManager = (ConnectivityManager) ((RockPlayer) context) .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = connManager.getActiveNetworkInfo(); /******* EMULATOR HACK - false condition needs to be removed *****/ //if (false && (netInfo == null || !netInfo.isConnected())){ if ((netInfo == null || !netInfo.isConnected())) { Bundle data = new Bundle(); data.putString("info", "No Internet Connection"); Message msg = new Message(); msg.setData(data); ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg); return; } /* * Get location */ MIN_UPDATE_INTVL = 5 * 24 * 60 * 60 * 1000; // 5 days SPREAD_INTVL = 21 * 24 * 60 * 60 * 1000; // 21 days; Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setPowerRequirement(Criteria.POWER_LOW); LocationManager locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (locManager.getBestProvider(criteria, true) != null) myLocation = locManager.getLastKnownLocation(locManager.getBestProvider(criteria, true)); else { myLocation = new Location("gps"); myLocation.setLatitude(47.100301); myLocation.setLongitude(-119.982465); } /* * Get preferred distance */ // SharedPreferences prefs = ((Filex) context).getSharedPreferences(((Filex) context).PREFS_NAME, 0); RockOnPreferenceManager prefs = new RockOnPreferenceManager(((RockPlayer) context).FILEX_PREFERENCES_PATH); concertRadius = prefs.getLong("ConcertRadius", (long) (((RockPlayer) context).CONCERT_RADIUS_DEFAULT)); //myLocation = locManager.getLastKnownLocation(locManager.getBestProvider(Criteria.POWER_LOW, true)); // try { // getArtistEvents(); // } catch (SAXException e) { // e.printStackTrace(); // } catch (ParserConfigurationException e) { // e.printStackTrace(); // } }
From source file:com.tingbacke.wearmaps.MobileActivity.java
/** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa.//from w ww.ja v a 2 s. c om * <p/> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); mMap.setMyLocationEnabled(true); /** * https://geolocation.ws/map/55.588227,13.002735/13/en?types=&limit=300&licenses= * Dammfrivgen 61 = 55.587116, 12.979788 */ /* mMap.addMarker(new MarkerOptions().position(new LatLng(55.61015, 12.9786)).title("Cykelpump Kockums Torg")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.5877, 12.9887)).title("Cykelpump Malm gamla stadion")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6093, 12.9967)).title("Cykelpump, Anna Linds plats")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6025, 12.9679)).title("Cykelpump, Ribersborgsstigen")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6131, 12.9767)).title("Turning Torso")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6140, 12.9839)).title("Stapelbddsparken, skatepark")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6125, 12.9914)).title("Media Evolution City")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6144, 12.9895)).title("Doc Piazza Trattoria")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6156, 12.9857)).title("Kranen K3, Malm Hgskola")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6150, 12.9858)).title("Ubtshallen")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6108, 12.9949)).title("Orkanen, Malm Hgskola")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.5850, 12.9873)).title("Swedbank Stadion")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.5922, 12.9975)).title("Pildammsparken Entr")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.5901, 12.9887)).title("Pildammsparken Tallriken")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.5890, 12.9825)).title("Jet bensinmack, Lorensborg")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6048, 12.9658)).title("Ribersborgs Kallbadhus")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6041, 12.9735)).title("Toalett, Ribersborgsstigen")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6086, 12.9774)).title("Kockum fritid")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6138, 12.9812)).title("Varvsparken")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6137, 12.9725)).title("Daniabadet, Vstra Hamnen")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.6171, 12.9744)).title("Scaniabadet, Vstra Hamnen")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.5967, 13.0053)).title("MALM")); mMap.addMarker(new MarkerOptions().position(new LatLng(55.5986, 12.9836)).title("Kronprinsen")); //mMap.addMarker(new MarkerOptions().position(new LatLng()).title("")); */ // Get LocationManager object from System Service LOCATION_SERVICE LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Create a criteria object to retrieve provider Criteria criteria = new Criteria(); // Get the name of the best provider String provider = locationManager.getBestProvider(criteria, true); // Get Current Location Location myLocation = locationManager.getLastKnownLocation(provider); // Get latitude of the current location double latitude = myLocation.getLatitude(); // Get longitude of the current location double longitude = myLocation.getLongitude(); // Create a LatLng object for the current location LatLng latLng = new LatLng(latitude, longitude); // Show the current location in Google Map mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(18).bearing(0).tilt(25) .build(); mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); LatLng myCoordinates = new LatLng(latitude, longitude); CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myCoordinates, 18); mMap.animateCamera(yourLocation); }
From source file:com.example.scandevice.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext();// w w w. j a va2s .com LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); // Getting the name of the provider that meets the criteria provider = locationManager.getBestProvider(criteria, true); if (provider == null && !locationManager.isProviderEnabled(provider)) { // Get the location from the given provider List<String> list = locationManager.getAllProviders(); for (int i = 0; i < list.size(); i++) { //Get device name; String temp = list.get(i); //check usable if (locationManager.isProviderEnabled(temp)) { provider = temp; break; } } } //get location where reference last. Location location = locationManager.getLastKnownLocation(provider); if (location == null) Toast.makeText(this, "There are no available position information providers.", Toast.LENGTH_SHORT) .show(); else //GPS start from last location. onLocationChanged(location); // Set by <content src="index.html" /> in config.xml loadUrl(launchUrl); }
From source file:edu.pdx.cecs.orcycle.MyApplication.java
public Location getLastKnownLocation() { LocationManager lm = null; List<String> providers = null; Location location = null;/*from w w w. j a v a2 s. c om*/ if (null != (lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE))) { if (null != (providers = lm.getProviders(true))) { /* Loop over the array backwards, and if you get a location, then break out the loop*/ for (int i = providers.size() - 1; i >= 0; --i) { if (null != (location = lm.getLastKnownLocation(providers.get(i)))) { break; } } } } return location; }
From source file:com.projectattitude.projectattitude.Activities.MapActivity.java
/** * Handles everything/*from w w w.ja v a 2 s. c o m*/ * @param map */ @Override public void onMapReady(GoogleMap map) { mMap = map; LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); if (ContextCompat.checkSelfPermission(MapActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MapActivity.this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, MY_PERMISSION_ACCESS_COARSE_LOCATION); } /** * http://stackoverflow.com/questions/18425141/android-google-maps-api-v2-zoom-to-current-location 4/1/2017 4:20pm */ Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); if (location != null) { map.animateCamera(CameraUpdateFactory .newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13)); CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user .zoom(15) // Sets the zoom .bearing(0) // Sets the orientation of the camera to east .tilt(40) // Sets the tilt of the camera to 30 degrees .build(); // Creates a CameraPosition from the builder map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } enableMyLocation(); //couldn't get ColorMap to work, so made one for the meantime HashMap<String, BitmapDescriptor> hm = new HashMap<String, BitmapDescriptor>(); hm.put("Anger", BitmapDescriptorFactory.fromResource(R.drawable.ic_anger_colour_36px));//defaultMarker(356)); hm.put("Confusion", BitmapDescriptorFactory.fromResource(R.drawable.ic_confusion_colour_36px));//defaultMarker(19)); hm.put("Disgust", BitmapDescriptorFactory.fromResource(R.drawable.ic_disgust_colour_36px));//defaultMarker(65)); hm.put("Fear", BitmapDescriptorFactory.fromResource(R.drawable.ic_fear_colour_36px));//defaultMarker(42)); hm.put("Happiness", BitmapDescriptorFactory.fromResource(R.drawable.ic_happiness_colour_36px));//defaultMarker(160)); hm.put("Sadness", BitmapDescriptorFactory.fromResource(R.drawable.ic_sadness_colour_36px));//defaultMarker(60)); hm.put("Shame", BitmapDescriptorFactory.fromResource(R.drawable.ic_shame_colour_36px));//defaultMarker(200)); hm.put("Surprise", BitmapDescriptorFactory.fromResource(R.drawable.ic_surprise_colour_36px));//defaultMarker(22)); //Taken from https://developers.google.com/maps/documentation/android-api/marker //On March 21st at 17:53 map.setOnInfoWindowClickListener(this); if (getIntent().hasExtra("users")) { ArrayList<User> users = (ArrayList<User>) getIntent().getSerializableExtra("users"); GPSTracker gps = new GPSTracker(MapActivity.this); //LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); //LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { latitude = Math.round(gps.getLatitude() * 10000d) / 10000d; longitude = Math.round(gps.getLongitude() * 10000d) / 10000d; if (latitude != 0 & longitude != 0) { Toast.makeText(MapActivity.this, "Found your location", Toast.LENGTH_LONG).show(); Log.d("Distance", "Current Location: " + latitude + " " + longitude); for (int i = 0; i < users.size(); i++) { Mood mood = users.get(i).getFirstMood(); // if(mood.getLatitude()!= null && mood.getLongitude() != null) { if (mood != null) { Double returned = calculateDistance(latitude, longitude, mood.getLatitude(), mood.getLongitude()); returned = returned / 1000; Log.d("Distance", "Current Distance: " + returned); Log.d("Distance", "Current comparison to: " + users.get(i).getUserName() + " " + mood.getEmotionState()); if (returned < 5) { map.addMarker(new MarkerOptions() .position(new LatLng(mood.getLatitude(), mood.getLongitude())) .title(mood.getMaker()).snippet(mood.getEmotionState()) .icon(hm.get(mood.getEmotionState()))).setTag(mood); } } } } else { Toast.makeText(MapActivity.this, "Could not find your location, please try again!", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(MapActivity.this, "Please turn on GPS for locations!", Toast.LENGTH_LONG).show(); } } else if (getIntent().hasExtra("user")) { ArrayList<Mood> userMoodList = (ArrayList<Mood>) getIntent().getSerializableExtra("user"); for (int i = 0; i < userMoodList.size(); i++) { //TODO this will get EVERY mood from the user, which could be too many Mood mood = userMoodList.get(i); if (mood.getLongitude() == 0 && mood.getLatitude() == 0) { Log.d("MapMoods", "Mood: " + mood.getEmotionState() + "not mapped"); } else { map.addMarker(new MarkerOptions().position(new LatLng(mood.getLatitude(), mood.getLongitude())) .title(mood.getMaker()).snippet(mood.getEmotionState()) .icon(hm.get(mood.getEmotionState()))).setTag(mood); } } } else { Toast.makeText(MapActivity.this, "MIts Fucked, nothing go passed", Toast.LENGTH_LONG).show(); } }
From source file:com.rizal.lovins.smartkasir.activity.SettingsActivity.java
private void location() { LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return;/*w w w. j a v a 2 s .co m*/ } Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { new AlertDialog.Builder(SettingsActivity.this).setTitle("Location") .setMessage("lat: " + location.getLatitude() + ", long: " + location.getLongitude()) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } }