android.location.LocationManager Java Examples
The following examples show how to use
android.location.LocationManager.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BacKService.java From kute with Apache License 2.0 | 6 votes |
@Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); resultReceiver = intent.getParcelableExtra("receiver"); this.m_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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. } this.m_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 5, this); this.m_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 5, this); return START_STICKY; }
Example #2
Source File: PermissionUtil.java From DoraemonKit with Apache License 2.0 | 6 votes |
/** * 检测是否有定位权限,不可靠,比如在室内打开app,这种情况下定位模块没有值,会报无权限 * * @return */ @SuppressLint("MissingPermission") public static boolean checkLocationUnreliable(Context context) { try { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return false; } Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Location location2 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); return location != null || location2 != null; } catch (Exception e) { return false; } }
Example #3
Source File: MapLocationUtil.java From lunzi with Apache License 2.0 | 6 votes |
private String getProvider(LocationManager locationManager) { // 构建位置查询条件 Criteria criteria = new Criteria(); // 查询精度:高 criteria.setAccuracy(Criteria.ACCURACY_FINE); // 速度 criteria.setSpeedRequired(false); // 是否查询海拨:否 criteria.setAltitudeRequired(false); // 是否查询方位角:否 criteria.setBearingRequired(false); // 电量要求:低 criteria.setPowerRequirement(Criteria.POWER_LOW); // 返回最合适的符合条件的provider,第2个参数为true说明,如果只有一个provider是有效的,则返回当前provider return locationManager.getBestProvider(criteria, true); }
Example #4
Source File: AppLocationFragment.java From GooglePlayServiceLocationSupport with Apache License 2.0 | 6 votes |
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGoogleApiAvailability = GoogleApiAvailability.getInstance(); mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API). addConnectionCallbacks(this).addOnConnectionFailedListener(this).build(); mLocationService = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mLocationRequest = LocationRequest.create(); Bundle bundle = getArguments(); if (bundle != null) enableUpdates = bundle.getBoolean(AppLocation.REQUEST_UPDATES, true); else enableUpdates = true; }
Example #5
Source File: LooperThread.java From PocketMaps with MIT License | 6 votes |
/** * * @param context * @param useProvider * @param minTimeFilter * @param minTimeGpsProvider * @param minTimeNetProvider * @param locationListener * @param forwardProviderUpdates */ LooperThread( Context context, UseProvider useProvider, long minTimeFilter, long minTimeGpsProvider, long minTimeNetProvider, LocationListener locationListener, boolean forwardProviderUpdates) { mContext = context; mClientHandler = new Handler(); mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mUseProvider = useProvider; mMinTimeFilter = minTimeFilter; mMinTimeGpsProvider = minTimeGpsProvider; mMinTimeNetProvider = minTimeNetProvider; mClientLocationListener = locationListener; mForwardProviderUpdates = forwardProviderUpdates; start(); }
Example #6
Source File: ShellLocationModeSetting.java From test-butler with Apache License 2.0 | 6 votes |
@RequiresApi(api = Build.VERSION_CODES.KITKAT) int getLocationMode() { String locationProviders = getLocationProviders(); boolean gps = isProviderEnabled(locationProviders, LocationManager.GPS_PROVIDER); boolean network = isProviderEnabled(locationProviders, LocationManager.NETWORK_PROVIDER); if (gps && network) { return Settings.Secure.LOCATION_MODE_HIGH_ACCURACY; } else if (gps) { return Settings.Secure.LOCATION_MODE_SENSORS_ONLY; } else if (network) { return Settings.Secure.LOCATION_MODE_BATTERY_SAVING; } else { return Settings.Secure.LOCATION_MODE_OFF; } }
Example #7
Source File: LocationSubjectTest.java From android-test with Apache License 2.0 | 6 votes |
@Test public void isAt_notAt() { Location location = new Location(LocationManager.GPS_PROVIDER); location.setLatitude(1); location.setLongitude(-1); Location other = new Location(LocationManager.GPS_PROVIDER); other.setLatitude(1); other.setLongitude(-2); try { assertThat(location).isAt(other); fail(); } catch (AssertionError e) { assertThat(e).factValue("expected").isEqualTo("-2.0"); assertThat(e).factValue("but was").isEqualTo("-1.0"); } }
Example #8
Source File: LocationLogic.java From redalert-android with Apache License 2.0 | 6 votes |
public static Location GetLastKnownLocation(Context context) { // Get location manager LocationManager locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE); // Create location criteria Criteria criteria = new Criteria(); // Set fine accuracy criteria.setAccuracy(criteria.ACCURACY_FINE); // Get best provider String bestProvider = locationManager.getBestProvider(criteria, false); // No provider? if (bestProvider == null) { // Return null return null; } // Return last location return locationManager.getLastKnownLocation(bestProvider); }
Example #9
Source File: LocationManagerService.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Returns all providers by name, including passive and the ones that are not permitted to * be accessed by the calling activity or are currently disabled, but excluding fused. */ @Override public List<String> getAllProviders() { ArrayList<String> out; synchronized (mLock) { out = new ArrayList<>(mProviders.size()); for (LocationProviderInterface provider : mProviders) { String name = provider.getName(); if (LocationManager.FUSED_PROVIDER.equals(name)) { continue; } out.add(name); } } if (D) Log.d(TAG, "getAllProviders()=" + out); return out; }
Example #10
Source File: GeoPointActivity.java From commcare-android with Apache License 2.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(StringUtils.getStringRobust(this, R.string.application_name) + " > " + StringUtils.getStringRobust(this, R.string.get_location)); locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); providers = GeoUtils.evaluateProviders(locationManager); setupLocationDialog(); long mLong = -1; if (savedInstanceState != null) { mLong = savedInstanceState.getLong("millisRemaining", -1); } if (mLong > 0) { mTimer = new TimeoutTimer(mLong, this); } else { mTimer = new TimeoutTimer(HiddenPreferences.getGpsWidgetTimeoutInMilliseconds(), this); } mTimer.start(); }
Example #11
Source File: LocationProvider.java From android-chromium with BSD 2-Clause "Simplified" License | 6 votes |
private boolean usePassiveOneShotLocation() { if (!isOnlyPassiveLocationProviderEnabled()) return false; // Do not request a location update if the only available location provider is // the passive one. Make use of the last known location and call // onLocationChanged directly. final Location location = mLocationManager.getLastKnownLocation( LocationManager.PASSIVE_PROVIDER); if (location != null) { ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { updateNewLocation(location); } }); } return true; }
Example #12
Source File: DeviceLocation.java From kickflip-android-sdk with Apache License 2.0 | 6 votes |
/** * Get the last known location. * If one is not available, fetch * a fresh location * * @param context * @param waitForGpsFix * @param cb */ public static void getLastKnownLocation(Context context, boolean waitForGpsFix, final LocationResult cb) { DeviceLocation deviceLocation = new DeviceLocation(); LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Location last_loc; last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (last_loc == null) last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (last_loc != null && cb != null) { cb.gotLocation(last_loc); } else { deviceLocation.getLocation(context, cb, waitForGpsFix); } }
Example #13
Source File: ActivityEditLocation2.java From fingen with Apache License 2.0 | 6 votes |
@NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}) void startDetectCoords() { if (location.getID() < 0) { locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (locationManager != null && locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } if (locationManager != null && locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); } } }
Example #14
Source File: MainActivity.java From good-weather with GNU General Public License v3.0 | 6 votes |
public void gpsRequestLocation() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Looper locationLooper = Looper.myLooper(); locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mLocationListener, locationLooper); final Handler locationHandler = new Handler(locationLooper); locationHandler.postDelayed(new Runnable() { @Override public void run() { locationManager.removeUpdates(mLocationListener); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (lastLocation != null) { mLocationListener.onLocationChanged(lastLocation); } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener); } } } }, LOCATION_TIMEOUT_IN_MS); } }
Example #15
Source File: GpsConnection.java From WhereYouGo with GNU General Public License v3.0 | 6 votes |
private synchronized void handleOnLocationChanged(Location location) { // Logger.d(TAG, "handleOnLocationChanged(), fix:" + isFixed + ", loc:" + location); if (!isFixed) { if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) { if (Preferences.GPS_BEEP_ON_GPS_FIX) UtilsAudio.playBeep(1); disableNetwork(); isFixed = true; } LocationState.onLocationChanged(location); } else { if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) { LocationState.onLocationChanged(location); setNewTimer(); } else { // do not send location } } }
Example #16
Source File: LocationHelper.java From MVPAndroidBootstrap with Apache License 2.0 | 6 votes |
public static Location getLastKnownLocation(Context context) { LocationManager mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); Location bestLocation = null; for (String provider : providers) { Location l = mLocationManager.getLastKnownLocation(provider); if (l == null) { continue; } if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { // Found best last known location: %s", l); bestLocation = l; } } return bestLocation; }
Example #17
Source File: GeolocationTracker.java From delion with Apache License 2.0 | 6 votes |
/** * Requests an updated location if the last known location is older than maxAge milliseconds. * * Note: this must be called only on the UI thread. */ @SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC") static void refreshLastKnownLocation(Context context, long maxAge) { ThreadUtils.assertOnUiThread(); // We're still waiting for a location update. if (sListener != null) return; LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location == null || getLocationAge(location) > maxAge) { String provider = LocationManager.NETWORK_PROVIDER; if (locationManager.isProviderEnabled(provider)) { sListener = new SelfCancelingListener(locationManager); locationManager.requestSingleUpdate(provider, sListener, null); } } }
Example #18
Source File: LocationState.java From WhereYouGo with GNU General Public License v3.0 | 6 votes |
static void onStatusChanged(String provider, int status, Bundle extras) { Logger.w(TAG, "onStatusChanged(" + provider + ", " + status + ", " + extras + ")"); for (int i = 0; i < mListeners.size(); i++) { mListeners.get(i).onStatusChanged(provider, status, extras); } // status 1 - provider disabled // status 2 - provider enabled // if GPS provider is disabled, set location only as network if (provider.equals(LocationManager.GPS_PROVIDER) && status == 1) { if (LocationState.location != null) { LocationState.location.setProvider(LocationManager.NETWORK_PROVIDER); onLocationChanged(LocationState.location); } } // uncomment if GPS must be enabled // if (provider.equals(LocationManager.GPS_PROVIDER) && status == 1) { // setGpsOff(null); // } }
Example #19
Source File: LocationService.java From AndroidLocationStarterKit with MIT License | 5 votes |
@Override public void onProviderDisabled(String provider) { if (provider.equals(LocationManager.GPS_PROVIDER)) { notifyLocationProviderStatusUpdated(false); } }
Example #20
Source File: GpsSampleFragment.java From genymotion-binocle with Apache License 2.0 | 5 votes |
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); locationManager = (LocationManager) this.getActivity().getSystemService(Context.LOCATION_SERVICE); locationListener = new MyLocationListener(); }
Example #21
Source File: TrackerService.java From android_maplibui with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void onLocationChanged(Location location) { boolean update = LocationUtil.isProviderEnabled(this, location.getProvider(), true); if (!mIsRunning || !update) return; if (mHasGPSFix && !location.getProvider().equals(LocationManager.GPS_PROVIDER)) return; String fixType = location.hasAltitude() ? "3d" : "2d"; mValues.clear(); mValues.put(TrackLayer.FIELD_SESSION, mTrackId); mPoint.setCoordinates(location.getLongitude(), location.getLatitude()); mPoint.setCRS(GeoConstants.CRS_WGS84); mPoint.project(GeoConstants.CRS_WEB_MERCATOR); mValues.put(TrackLayer.FIELD_LON, mPoint.getX()); mValues.put(TrackLayer.FIELD_LAT, mPoint.getY()); mValues.put(TrackLayer.FIELD_ELE, location.getAltitude()); mValues.put(TrackLayer.FIELD_FIX, fixType); mValues.put(TrackLayer.FIELD_SAT, mSatellitesCount); mValues.put(TrackLayer.FIELD_SPEED, location.getSpeed()); mValues.put(TrackLayer.FIELD_ACCURACY, location.getAccuracy()); mValues.put(TrackLayer.FIELD_SENT, 0); mValues.put(TrackLayer.FIELD_TIMESTAMP, location.getTime()); try { getContentResolver().insert(mContentUriTrackPoints, mValues); } catch (Exception ignored) { } }
Example #22
Source File: Engine.java From tilt-game-android with MIT License | 5 votes |
public void enableLocationSensor(final Context pContext, final ILocationListener pLocationListener, final LocationSensorOptions pLocationSensorOptions) { this.mLocationListener = pLocationListener; final LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE); final String locationProvider = locationManager.getBestProvider(pLocationSensorOptions, pLocationSensorOptions.isEnabledOnly()); // TODO locationProvider can be null, in that case return false. Successful case should return true. locationManager.requestLocationUpdates(locationProvider, pLocationSensorOptions.getMinimumTriggerTime(), pLocationSensorOptions.getMinimumTriggerDistance(), this); this.onLocationChanged(locationManager.getLastKnownLocation(locationProvider)); }
Example #23
Source File: LocationUtils.java From arcusandroid with Apache License 2.0 | 5 votes |
public static Location getLastKnownCoarseLocation(@NonNull Context context) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); // Walk through each enabled location provider and return the first found, last-known location for (String thisLocProvider : locationManager.getProviders(true)) { Location lastKnown = locationManager.getLastKnownLocation(thisLocProvider); if (lastKnown != null) { return lastKnown; } } // Always possible there's no means to determine location return null; }
Example #24
Source File: LocationActivity.java From Conversations with GNU General Public License v3.0 | 5 votes |
@Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Context ctx = getApplicationContext(); setTheme(ThemeHelper.find(this)); final PackageManager packageManager = ctx.getPackageManager(); hasLocationFeature = packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION) || packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS) || packageManager.hasSystemFeature(PackageManager.FEATURE_LOCATION_NETWORK); this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); this.marker_icon = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.marker); // Ask for location permissions if location services are enabled and we're // just starting the activity (we don't want to keep pestering them on every // screen rotation or if there's no point because it's disabled anyways). if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && savedInstanceState == null) { requestPermissions(REQUEST_CODE_CREATE); } final IConfigurationProvider config = Configuration.getInstance(); config.load(ctx, getPreferences()); config.setUserAgentValue(BuildConfig.APPLICATION_ID + "/" + BuildConfig.VERSION_CODE); if (QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor)) { try { config.setHttpProxy(HttpConnectionManager.getProxy()); } catch (IOException e) { throw new RuntimeException("Unable to configure proxy"); } } }
Example #25
Source File: LocationProvider.java From open-location-code with Apache License 2.0 | 5 votes |
@AutoFactory public LocationProvider( @Provided GoogleApiAvailability googleApiAvailability, @Provided GoogleApiClient googleApiClient, @Provided FusedLocationProviderApi fusedLocationProviderApi, @Provided LocationManager locationManager, @Provided SensorManager sensorManager, @Provided Display displayManager, Context context, LocationCallback locationCallback) { this.mGoogleApiAvailability = googleApiAvailability; this.mGoogleApiClient = googleApiClient; this.mFusedLocationProviderApi = fusedLocationProviderApi; this.mLocationManager = locationManager; this.mContext = context; this.mLocationCallback = locationCallback; this.mSensorManager = sensorManager; this.mDisplay = displayManager; mLocationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(INTERVAL_IN_MS) .setFastestInterval(FASTEST_INTERVAL_IN_MS); mNetworkLocationListener = createLocationListener(); mGpsLocationListener = createLocationListener(); determineIfUsingGms(); if (isUsingGms()) { mGoogleApiClient.registerConnectionCallbacks(this); mGoogleApiClient.registerConnectionFailedListener(this); } }
Example #26
Source File: SearchCityFragment.java From prayer-times-android with Apache License 2.0 | 5 votes |
@SuppressWarnings("MissingPermission") @Override public void onPause() { if (PermissionUtils.get(getActivity()).pLocation) { LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); lm.removeUpdates(this); } super.onPause(); }
Example #27
Source File: GPSListener.java From cordova-android-chromeview with Apache License 2.0 | 5 votes |
/** * Start requesting location updates. * * @param interval */ @Override protected void start() { if (!this.running) { if (this.locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) { this.running = true; this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, this); } else { this.fail(CordovaLocationListener.POSITION_UNAVAILABLE, "GPS provider is not available."); } } }
Example #28
Source File: Androzic.java From Androzic with GNU General Public License v3.0 | 5 votes |
@Override public void onGpsStatusChanged(String provider, final int status, final int fsats, final int tsats) { if (LocationManager.GPS_PROVIDER.equals(provider)) { gpsStatus = status; gpsFSats = fsats; gpsTSats = tsats; } }
Example #29
Source File: GeoLocation.java From open-rmbt with Apache License 2.0 | 5 votes |
public GeoLocation(final Context context, final boolean gpsEnabled, final long minTime, final float minDistance) { locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); this.gpsEnabled = gpsEnabled; this.minTime = minTime; this.minDistance = minDistance; }
Example #30
Source File: AppLocationIntentService.java From GooglePlayServiceLocationSupport with Apache License 2.0 | 5 votes |
@Override public void onCreate() { super.onCreate(); mGoogleApiAvailability = GoogleApiAvailability.getInstance(); mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API). addConnectionCallbacks(this).addOnConnectionFailedListener(this).build(); mLocationService = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mLocationRequest = LocationRequest.create(); enableUpdates = true; if (!servicesConnected()) { if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) mGoogleApiClient.connect(); } }