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.appnexus.opensdk.AdRequest.java
private AdRequest(AdRequester adRequester, int httpRetriesLeft, int blankRetriesLeft) { owner = adRequester.getOwner();//from w w w . j a va2s . c o m this.requester = adRequester; this.httpRetriesLeft = httpRetriesLeft; this.blankRetriesLeft = blankRetriesLeft; this.placementId = owner.getPlacementID(); context = owner.getContext(); String aid = android.provider.Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); // Do we have access to location? if (context.checkCallingOrSelfPermission( "android.permission.ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED || context.checkCallingOrSelfPermission( "android.permission.ACCESS_COARSE_LOCATION") == PackageManager.PERMISSION_GRANTED) { // Get lat, long from any GPS information that might be currently // available LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Location lastLocation = lm.getLastKnownLocation(lm.getBestProvider(new Criteria(), false)); if (lastLocation != null) { lat = "" + lastLocation.getLatitude(); lon = "" + lastLocation.getLongitude(); locDataAge = "" + (System.currentTimeMillis() - lastLocation.getTime()); locDataPrecision = "" + lastLocation.getAccuracy(); } } else { Clog.w(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_location)); } // Do we have permission ACCESS_NETWORK_STATE? if (context.checkCallingOrSelfPermission( "android.permission.ACCESS_NETWORK_STATE") != PackageManager.PERMISSION_GRANTED) { Clog.e(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_network_state)); fail(); this.cancel(true); return; } // Get orientation, the current rotation of the device orientation = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? "h" : "v"; // Get hidmd5, hidsha1, the device ID hashed if (Settings.getSettings().hidmd5 == null) { Settings.getSettings().hidmd5 = HashingFunctions.md5(aid); } hidmd5 = Settings.getSettings().hidmd5; if (Settings.getSettings().hidsha1 == null) { Settings.getSettings().hidsha1 = HashingFunctions.sha1(aid); } hidsha1 = Settings.getSettings().hidsha1; // Get devMake, devModel, the Make and Model of the current device devMake = Settings.getSettings().deviceMake; devModel = Settings.getSettings().deviceModel; // Get carrier if (Settings.getSettings().carrierName == null) { Settings.getSettings().carrierName = ((TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName(); } carrier = Settings.getSettings().carrierName; // Get firstlaunch and convert it to a string firstlaunch = Settings.getSettings().first_launch; // Get ua, the user agent... ua = Settings.getSettings().ua; // Get wxh if (owner.isBanner()) { this.width = ((BannerAdView) owner).getAdWidth(); this.height = ((BannerAdView) owner).getAdHeight(); } maxHeight = owner.getContainerHeight(); maxWidth = owner.getContainerWidth(); if (Settings.getSettings().mcc == null || Settings.getSettings().mnc == null) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String networkOperator = tm.getNetworkOperator(); if (networkOperator != null && networkOperator.length() >= 6) { Settings.getSettings().mcc = networkOperator.substring(0, 3); Settings.getSettings().mnc = networkOperator.substring(3); } } mcc = Settings.getSettings().mcc; mnc = Settings.getSettings().mnc; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); connection_type = wifi.isConnected() ? "wifi" : "wan"; dev_time = "" + System.currentTimeMillis(); if (owner instanceof InterstitialAdView) { // Make string for allowed_sizes allowedSizes = ""; ArrayList<Size> sizes = ((InterstitialAdView) owner).getAllowedSizes(); for (Size s : sizes) { allowedSizes += "" + s.width() + "x" + s.height(); // If not last size, add a comma if (sizes.indexOf(s) != sizes.size() - 1) allowedSizes += ","; } } nativeBrowser = owner.getOpensNativeBrowser() ? "1" : "0"; //Reserve price reserve = owner.getReserve(); if (reserve <= 0) { this.psa = owner.shouldServePSAs ? "1" : "0"; } else { this.psa = "0"; } age = owner.getAge(); if (owner.getGender() != null) { if (owner.getGender() == AdView.GENDER.MALE) { gender = "m"; } else if (owner.getGender() == AdView.GENDER.FEMALE) { gender = "f"; } else { gender = null; } } customKeywords = owner.getCustomKeywords(); mcc = Settings.getSettings().mcc; mnc = Settings.getSettings().mnc; language = Settings.getSettings().language; }
From source file:com.cloudbees.gasp.activity.GaspLocationsActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_locations); GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); LocationManager locationManager; String svcName = Context.LOCATION_SERVICE; locationManager = (LocationManager) getSystemService(svcName); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false);//from ww w . ja v a 2 s. com criteria.setSpeedRequired(false); criteria.setCostAllowed(true); String provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); Log.i(TAG, "CURRENT LOCATION"); Log.i(TAG, "Latitude = " + location.getLatitude()); Log.i(TAG, "Longitude = " + location.getLongitude()); if (location != null) { double latitude = location.getLatitude(); double longitude = location.getLongitude(); Geocoder gc = new Geocoder(this, Locale.getDefault()); if (!Geocoder.isPresent()) Log.i(TAG, "No geocoder available"); else { try { List<Address> addresses = gc.getFromLocation(latitude, longitude, 1); StringBuilder sb = new StringBuilder(); if (addresses.size() > 0) { Address address = addresses.get(0); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) sb.append(address.getAddressLine(i)).append(" "); sb.append(address.getLocality()).append(""); sb.append(address.getPostalCode()).append(" "); sb.append(address.getCountryName()); } Log.i(TAG, "Address: " + sb.toString()); } catch (IOException e) { Log.d(TAG, "IOException getting address from geocoder", e); } } } map.setMyLocationEnabled(true); LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude()); CameraPosition cameraPosition = new CameraPosition.Builder().target(myLocation).zoom(16).bearing(0).tilt(0) .build(); map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); new LocationMapper().execute(); }
From source file:org.akvo.flow.activity.GeoshapeActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.geoshape_activity); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mFeatures = new ArrayList<>(); mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); mFeatureMenu = findViewById(R.id.feature_menu); mFeatureName = (TextView) findViewById(R.id.feature_name); mClearPointBtn = findViewById(R.id.clear_point_btn); mClearPointBtn.setOnClickListener(mFeatureMenuListener); findViewById(R.id.add_point_btn).setOnClickListener(mFeatureMenuListener); findViewById(R.id.clear_feature_btn).setOnClickListener(mFeatureMenuListener); findViewById(R.id.properties).setOnClickListener(mFeatureMenuListener); mAllowPoints = getIntent().getBooleanExtra(ConstantUtil.EXTRA_ALLOW_POINTS, true); mAllowLine = getIntent().getBooleanExtra(ConstantUtil.EXTRA_ALLOW_LINE, true); mAllowPolygon = getIntent().getBooleanExtra(ConstantUtil.EXTRA_ALLOW_POLYGON, true); mManualInput = getIntent().getBooleanExtra(ConstantUtil.EXTRA_MANUAL_INPUT, true); initMap();//from w w w . j a v a 2 s . c o m String geoJSON = getIntent().getStringExtra(ConstantUtil.GEOSHAPE_RESULT); if (!TextUtils.isEmpty(geoJSON)) { load(geoJSON); } else { // If user location is known, center map LocationManager manager = (LocationManager) 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) { LatLng position = new LatLng(location.getLatitude(), location.getLongitude()); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 10)); } } } }
From source file:com.andybotting.tubechaser.activity.StationDetail.java
/** * Upload stats/* w w w . ja va 2 s .c o m*/ */ private void uploadStats() { if (LOGV) Log.v(TAG, "Sending Station/Line statistics"); // gather all of the device info try { TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String device_uuid = tm.getDeviceId(); String device_id = "00000000000000000000000000000000"; if (device_uuid != null) { device_id = GenericUtil.MD5(device_uuid); } LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // post the data HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://tubechaser.andybotting.com/stats/depart/send"); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("device_id", device_id)); pairs.add(new BasicNameValuePair("station_id", String.valueOf(mStation.getId()))); pairs.add(new BasicNameValuePair("line_id", String.valueOf(mLine.getId()))); if (location != null) { pairs.add(new BasicNameValuePair("latitude", String.valueOf(location.getLatitude()))); pairs.add(new BasicNameValuePair("longitude", String.valueOf(location.getLongitude()))); pairs.add(new BasicNameValuePair("accuracy", String.valueOf(location.getAccuracy()))); } try { post.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { HttpResponse response = client.execute(post); response.getStatusLine().getStatusCode(); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.andybotting.tramhunter.activity.StopDetailsActivity.java
/** * Upload statistics to our web server// w w w . ja va 2 s . co m */ private void uploadStats() { if (LOGV) Log.i(TAG, "Sending stop request statistics"); // gather all of the device info try { TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String device_uuid = tm.getDeviceId(); String device_id = "00000000000000000000000000000000"; if (device_uuid != null) { device_id = GenericUtil.MD5(device_uuid); } LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // post the data HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://tramhunter.andybotting.com/stats/stop/send"); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("device_id", device_id)); pairs.add(new BasicNameValuePair("guid", ttService.getGUID())); pairs.add(new BasicNameValuePair("ttid", String.valueOf(mStop.getTramTrackerID()))); if (location != null) { pairs.add(new BasicNameValuePair("latitude", String.valueOf(location.getLatitude()))); pairs.add(new BasicNameValuePair("longitude", String.valueOf(location.getLongitude()))); pairs.add(new BasicNameValuePair("accuracy", String.valueOf(location.getAccuracy()))); } try { post.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { HttpResponse response = client.execute(post); response.getStatusLine().getStatusCode(); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.adflake.AdFlakeManager.java
/** * Gets the current location./*from w w w .j av a 2s . c o m*/ * * @note If location is not enabled, this method will return null * @return the current location or null if location access is not enabled or * granted by the user. */ public Location getCurrentLocation() { if (_contextReference == null) { return null; } Context context = _contextReference.get(); if (context == null) { return null; } Location location = null; if (context.checkCallingOrSelfPermission( android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); } else if (context.checkCallingOrSelfPermission( android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } return location; }
From source file:net.freifunk.android.discover.Main.java
private LatLng getLocation() { // 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();//from w w w . j ava 2 s. co m } else { // Google Play Services are available // 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); return new LatLng(location.getLatitude(), location.getLongitude()); } return new LatLng(0, 0); }
From source file:edu.mit.mobile.android.locast.ver2.casts.LocatableListWithMap.java
/** * Gets the last-known location and updates with that. *//*from w ww . j av a 2 s . c om*/ private void updateLocation() { final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE); final String provider = lm.getBestProvider(new Criteria(), true); if (provider == null) { Toast.makeText(this, getString(R.string.error_no_providers), Toast.LENGTH_LONG).show(); finish(); return; } final Location loc = lm.getLastKnownLocation(provider); if (loc != null) { updateLocation(loc); } else { Toast.makeText(this, R.string.notice_finding_your_location, Toast.LENGTH_LONG).show(); setRefreshing(true); mMapView.setVisibility(View.VISIBLE); // show the map, even without location being found } mLastLocation = loc; }
From source file:com.findcab.driver.activity.Signup.java
/** * ?GPS?//from www. j a v a2s . c o m */ private void initLocation() { LocationManager locationManager; String serviceName = Context.LOCATION_SERVICE; locationManager = (LocationManager) this.getSystemService(serviceName); // ? Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); String provider = locationManager.getBestProvider(criteria, true); Location location = locationManager.getLastKnownLocation(provider); if (location != null) { lat = location.getLatitude(); lng = location.getLongitude(); } }
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 w w w. jav a 2 s .c o m*/ 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; } }); } } }