android.location.LocationListener Java Examples
The following examples show how to use
android.location.LocationListener.
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: BaseActivity.java From JsBridge with Apache License 2.0 | 6 votes |
public Location getLocation(LocationListener listener) { locationListener = listener; mLocationManager = (LocationManager) HiApplication.getInstance().getSystemService(Context.LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); String locationProvider = null; if (providers.contains(LocationManager.GPS_PROVIDER)) { //如果是GPS locationProvider = LocationManager.GPS_PROVIDER; } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) { //如果是Network locationProvider = LocationManager.NETWORK_PROVIDER; } Location location = mLocationManager.getLastKnownLocation(locationProvider); mLocationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener); return location; }
Example #2
Source File: MapboxFusedLocationEngineImpl.java From mapbox-events-android with MIT License | 6 votes |
@SuppressLint("MissingPermission") @Override public void requestLocationUpdates(@NonNull LocationEngineRequest request, @NonNull LocationListener listener, @Nullable Looper looper) throws SecurityException { super.requestLocationUpdates(request, listener, looper); // Start network provider along with gps if (shouldStartNetworkProvider(request.getPriority())) { try { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, request.getInterval(), request.getDisplacement(), listener, looper); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } } }
Example #3
Source File: GPSCollector.java From sensordatacollector with GNU General Public License v2.0 | 6 votes |
@Override public void onDeRegistered() { if(this.mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } if(Build.VERSION.SDK_INT >= 23 && !(ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { for(LocationListener ll : this.locationListeners) { this.locationManager.removeUpdates(ll); } } this.timer.cancel(); this.map = null; this.lastKnownLocation = null; }
Example #4
Source File: HistoryRecord.java From itag with GNU General Public License v3.0 | 6 votes |
public static void clear(Context context, String addr) { if (BuildConfig.DEBUG) Log.d(LT, "clear history" + addr); checkRecords(context); records.remove(addr); save(context); LocationListener locationListener = sLocationListeners.get(addr); sLocationListeners.remove(addr); notifyChange(); if (locationListener != null) { final LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); if (locationManager != null) { if (BuildConfig.DEBUG) Log.d(LT, "GPS removeUpdates on clear history" + addr); locationManager.removeUpdates(locationListener); } ITagApplication.faRemovedGpsRequestByConnect(); } }
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: LocationHooker.java From DoraemonKit with Apache License 2.0 | 6 votes |
/** * @param originService 原始对象 LocationManager#mService * @param proxy 生成的代理对象 * @param method 需要被代理的方法 LocationManager#mService.requestLocationUpdates(request, transport, intent, packageName) * @param args 代理方法的参数 request, transport, intent, packageName * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchFieldException */ @Override public Object onInvoke(Object originService, Object proxy, Method method, Object[] args) throws IllegalAccessException, InvocationTargetException, NoSuchFieldException { if (!GpsMockManager.getInstance().isMocking()) { return method.invoke(originService, args); } Object listenerTransport = args[1]; //LocationListener mListener 类型 Field mListenerField = listenerTransport.getClass().getDeclaredField("mListener"); mListenerField.setAccessible(true); LocationListener locationListener = (LocationListener) mListenerField.get(listenerTransport); LocationListenerProxy locationListenerProxy = new LocationListenerProxy(locationListener); //将原始的LocationListener替换为LocationListenerProxy mListenerField.set(listenerTransport, locationListenerProxy); mListenerField.setAccessible(false); return method.invoke(originService, args); }
Example #7
Source File: GPSServiceCommandTest.java From JayPS-AndroidApp with MIT License | 6 votes |
@SmallTest public void testHandlesRefreshInterval() throws Exception { when(_mockLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true); _serviceCommand.execute(_app); _serviceCommand.onGPSChangeState(new GPSChangeState(GPSChangeState.State.START)); ArgumentCaptor<LocationListener> locationListenerCaptor = ArgumentCaptor.forClass(LocationListener.class); verify(_mockLocationManager,timeout(200).times(1)).requestLocationUpdates( anyString(), anyLong(), anyFloat(), locationListenerCaptor.capture()); int refreshInterval = 200; _serviceCommand.onGPSRefreshChangeEvent(new ChangeRefreshInterval(refreshInterval)); verify(_mockLocationManager, timeout(200).times(1)).removeUpdates((LocationListener) anyObject()); verify(_mockLocationManager, timeout(200).times(1)).requestLocationUpdates( LocationManager.GPS_PROVIDER, refreshInterval, 2, locationListenerCaptor.getValue() ); }
Example #8
Source File: LocationListenerProxy.java From osmdroid with Apache License 2.0 | 5 votes |
public boolean startListening(final LocationListener pListener, final long pUpdateTime, final float pUpdateDistance) { boolean result = false; mListener = pListener; for (final String provider : mLocationManager.getProviders(true)) { if (LocationManager.GPS_PROVIDER.equals(provider) || LocationManager.NETWORK_PROVIDER.equals(provider)) { result = true; mLocationManager.requestLocationUpdates(provider, pUpdateTime, pUpdateDistance, this); } } return result; }
Example #9
Source File: GPSServiceCommandTest.java From JayPS-AndroidApp with MIT License | 5 votes |
@SmallTest public void testBroadcastEventOnLocationChange() throws Exception { when(_mockLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true); when(_mockDataStore.getFirstLocationLattitude()).thenReturn(1.0f); when(_mockDataStore.getFirstLocationLongitude()).thenReturn(3.0f); long ts = 1200000000000l; when(_mockTime.getCurrentTimeMilliseconds()).thenReturn(ts); _serviceCommand.execute(_app); _serviceCommand.onGPSChangeState(new GPSChangeState(BaseChangeState.State.START)); ArgumentCaptor<LocationListener> locationListenerCaptor = ArgumentCaptor.forClass(LocationListener.class); verify(_mockLocationManager,timeout(1000).times(1)).requestLocationUpdates( anyString(), anyLong(), anyFloat(), locationListenerCaptor.capture()); Location location = new Location("location"); LocationListener listenerArgument = locationListenerCaptor.getValue(); when(_mockTime.getCurrentTimeMilliseconds()).thenReturn(ts+10000); listenerArgument.onLocationChanged(location); ArgumentCaptor<NewLocation> captor = ArgumentCaptor.forClass(NewLocation.class); verify(_bus,timeout(1000).atLeast(1)).post(captor.capture()); int nb = 0; for (int i = 0; i < captor.getAllValues().size(); i++) { try { NewLocation newLocation = captor.getAllValues().get(i); nb++; } catch (ClassCastException e) { // other type } } assertEquals(2, nb); // 2: one with onGPSChangeState (saved one), one with onLocationChanged }
Example #10
Source File: GPSServiceCommandTest.java From JayPS-AndroidApp with MIT License | 5 votes |
@SmallTest public void testHandlesGPSStartCommand() throws Exception { when(_mockLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true); _serviceCommand.execute(_app); _serviceCommand.onGPSChangeState(new GPSChangeState(GPSChangeState.State.START)); verify(_mockLocationManager,timeout(2000).times(1)).requestLocationUpdates( anyString(), anyLong(), anyFloat(), any(LocationListener.class)); }
Example #11
Source File: LocationBasedCountryDetector.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Unregister an already registered listener */ protected void unregisterListener(LocationListener listener) { final long bid = Binder.clearCallingIdentity(); try { mLocationManager.removeUpdates(listener); } finally { Binder.restoreCallingIdentity(bid); } }
Example #12
Source File: MapboxFusedLocationEngineImplTest.java From mapbox-events-android with MIT License | 5 votes |
@Test public void requestLocationUpdatesIndoors() { LocationEngineRequest request = new LocationEngineRequest.Builder(10) .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build(); LocationEngineCallback<LocationEngineResult> callback = mock(LocationEngineCallback.class); Looper looper = mock(Looper.class); when(locationManagerMock.getBestProvider(any(Criteria.class), anyBoolean())).thenReturn("network"); engine.requestLocationUpdates(request, callback, looper); verify(locationManagerMock, times(1)).requestLocationUpdates(anyString(), anyLong(), anyFloat(), any(LocationListener.class), any(Looper.class)); }
Example #13
Source File: MapboxFusedLocationEngineImplTest.java From mapbox-events-android with MIT License | 5 votes |
@Test public void requestLocationUpdatesOutdoors() { LocationEngineRequest request = new LocationEngineRequest.Builder(10) .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build(); LocationEngineCallback<LocationEngineResult> callback = mock(LocationEngineCallback.class); Looper looper = mock(Looper.class); when(locationManagerMock.getBestProvider(any(Criteria.class), anyBoolean())).thenReturn("gps"); engine.requestLocationUpdates(request, callback, looper); verify(locationManagerMock, times(2)).requestLocationUpdates(anyString(), anyLong(), anyFloat(), any(LocationListener.class), any(Looper.class)); }
Example #14
Source File: MapboxFusedLocationEngineImplTest.java From mapbox-events-android with MIT License | 5 votes |
@Test public void createListener() { LocationEngineCallback<LocationEngineResult> callback = mock(LocationEngineCallback.class); LocationListener locationListener = mapboxFusedLocationEngineImpl.createListener(callback); Location mockLocation = getMockLocation(LATITUDE, LONGITUDE); locationListener.onLocationChanged(mockLocation); ArgumentCaptor<LocationEngineResult> argument = ArgumentCaptor.forClass(LocationEngineResult.class); verify(callback).onSuccess(argument.capture()); LocationEngineResult result = argument.getValue(); assertThat(result.getLastLocation()).isSameAs(mockLocation); }
Example #15
Source File: LocationEngineProxyTest.java From mapbox-events-android with MIT License | 5 votes |
@Test public void testAddListener() { AndroidLocationEngineImpl.AndroidLocationEngineCallbackTransport transport = new AndroidLocationEngineImpl.AndroidLocationEngineCallbackTransport(callback); when(engineImpl.createListener(callback)).thenReturn(transport); LocationListener locationListener = locationEngineProxy.getListener(callback); assertThat(locationListener).isSameAs(transport); assertThat(locationEngineProxy.getListenersCount()).isEqualTo(1); }
Example #16
Source File: MapboxFusedLocationEngineImplAdditionalTest2.java From mapbox-events-android with MIT License | 5 votes |
@Before public void setUp() { location = mock(Location.class); when(location.getLatitude()).thenReturn(1.0); when(location.getLongitude()).thenReturn(2.0); Context mockContext = mock(Context.class); mockLocationManager = mock(LocationManager.class); when(mockContext.getSystemService(anyString())).thenReturn(mockLocationManager); List<String> providers = new ArrayList<>(); providers.add(PROVIDER); when(mockLocationManager.getAllProviders()).thenReturn(providers); when(mockLocationManager.getBestProvider(any(Criteria.class), anyBoolean())) .thenReturn(LocationManager.GPS_PROVIDER); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) { LocationListener listener = (LocationListener) invocation.getArguments()[3]; listener.onProviderEnabled(PROVIDER); listener.onStatusChanged(PROVIDER, LocationProvider.AVAILABLE, null); listener.onLocationChanged(location); listener.onProviderDisabled(PROVIDER); return null; } }).when(mockLocationManager) .requestLocationUpdates(anyString(), anyLong(), anyFloat(), any(LocationListener.class), any(Looper.class)); engines.add(new LocationEngineProxy<>(new MapboxFusedLocationEngineImpl(mockContext))); engines.add(new LocationEngineProxy<>(new AndroidLocationEngineImpl(mockContext))); }
Example #17
Source File: AndroidLocationEngineImplTest.java From mapbox-events-android with MIT License | 5 votes |
@Test public void removeLocationUpdatesForValidListener() { LocationEngineCallback<LocationEngineResult> callback = mock(LocationEngineCallback.class); LocationEngineRequest request = new LocationEngineRequest.Builder(10) .setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY).build(); engine.requestLocationUpdates(request, callback, mock(Looper.class)); engine.removeLocationUpdates(callback); verify(locationManagerMock, times(1)).removeUpdates(any(LocationListener.class)); }
Example #18
Source File: AndroidLocationEngineImplTest.java From mapbox-events-android with MIT License | 5 votes |
@Test public void createListener() { LocationEngineCallback<LocationEngineResult> callback = mock(LocationEngineCallback.class); LocationListener locationListener = androidLocationEngineImpl.createListener(callback); Location mockLocation = getMockLocation(LATITUDE, LONGITUDE); locationListener.onLocationChanged(mockLocation); ArgumentCaptor<LocationEngineResult> argument = ArgumentCaptor.forClass(LocationEngineResult.class); verify(callback).onSuccess(argument.capture()); LocationEngineResult result = argument.getValue(); assertThat(result.getLastLocation()).isSameAs(mockLocation); }
Example #19
Source File: AndroidLocationEngineImpl.java From mapbox-events-android with MIT License | 5 votes |
@SuppressLint("MissingPermission") @Override public void removeLocationUpdates(@NonNull LocationListener listener) { if (listener != null) { locationManager.removeUpdates(listener); } }
Example #20
Source File: AndroidLocationEngineImpl.java From mapbox-events-android with MIT License | 5 votes |
@SuppressLint("MissingPermission") @Override public void requestLocationUpdates(@NonNull LocationEngineRequest request, @NonNull LocationListener listener, @Nullable Looper looper) throws SecurityException { // Pick best provider only if user has not explicitly chosen passive mode currentProvider = getBestProvider(request.getPriority()); locationManager.requestLocationUpdates(currentProvider, request.getInterval(), request.getDisplacement(), listener, looper); }
Example #21
Source File: LocationBasedCountryDetector.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Register a listener with a provider name */ protected void registerListener(String provider, LocationListener listener) { final long bid = Binder.clearCallingIdentity(); try { mLocationManager.requestLocationUpdates(provider, 0, 0, listener); } finally { Binder.restoreCallingIdentity(bid); } }
Example #22
Source File: LocationTracker.java From AIMSICDL with GNU General Public License v3.0 | 5 votes |
public LocationTracker(AimsicdService service, LocationListener extLocationListener) { this.context = service; this.extLocationListener = extLocationListener; lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); mLocationListener = new MyLocationListener(); prefs = context.getSharedPreferences( AimsicdService.SHARED_PREFERENCES_BASENAME, 0); mDbHelper = new AIMSICDDbAdapter(context); }
Example #23
Source File: LocationBasedCountryDetector.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Stop the current query without notifying the listener. */ @Override public synchronized void stop() { if (mLocationListeners != null) { for (LocationListener listener : mLocationListeners) { unregisterListener(listener); } mLocationListeners = null; } if (mTimer != null) { mTimer.cancel(); mTimer = null; } }
Example #24
Source File: LocationsGPSUpdater.java From itag with GNU General Public License v3.0 | 5 votes |
@Override public void cancelLocationUpdates(@NonNull LocationListener listener) { if (mLocationManager == null) { ErrorsObservable.toast(R.string.no_location_manager); return; } mLocationManager.removeUpdates(listener); }
Example #25
Source File: LocationUtils.java From DevUtils with Apache License 2.0 | 5 votes |
/** * 获取位置 ( 需要先判断是否开启了定位 ) * @param listener {@link LocationListener} * @param time 间隔时间 * @param distance 间隔距离 * @return {@link Location} */ @SuppressLint("MissingPermission") public static Location getLocation(final LocationListener listener, final long time, final float distance) { Location location = null; try { sLocationManager = AppUtils.getLocationManager(); if (isLocationEnabled()) { sLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, time, distance, listener); if (sLocationManager != null) { location = sLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { sLocationManager.removeUpdates(listener); return location; } } } if (isGpsEnabled()) { if (location == null) { sLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, time, distance, listener); if (sLocationManager != null) { location = sLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { sLocationManager.removeUpdates(listener); return location; } } } } } catch (Exception e) { LogPrintUtils.eTag(TAG, e, "getLocation"); } return location; }
Example #26
Source File: KalmanLocationManager.java From PocketMaps with MIT License | 4 votes |
/** * Register for {@link android.location.Location Location} estimates using the given LocationListener callback. * * * @param useProvider Specifies which of the native location providers to use, or a combination of them. * * @param minTimeFilter Minimum time interval between location estimates, in milliseconds. * Indicates the frequency of predictions to be calculated by the filter, * thus the frequency of callbacks to be received by the given location listener. * * @param minTimeGpsProvider Minimum time interval between GPS readings, in milliseconds. * If {@link UseProvider#NET UseProvider.NET} was set, this value is ignored. * * @param minTimeNetProvider Minimum time interval between Network readings, in milliseconds. * If {@link UseProvider#GPS UseProvider.GPS} was set, this value is ignored. * * @param listener A {@link android.location.LocationListener LocationListener} whose * {@link android.location.LocationListener#onLocationChanged(android.location.Location) onLocationChanged(Location)} * method will be called for each location estimate produced by the filter. It will also receive * the status updates from the native providers. * * @param forwardProviderReadings Also forward location readings from the native providers to the given listener. * Note that <i>status</i> updates will always be forwarded. * */ public void requestLocationUpdates( UseProvider useProvider, long minTimeFilter, long minTimeGpsProvider, long minTimeNetProvider, LocationListener listener, boolean forwardProviderReadings) { // Validate arguments if (useProvider == null) throw new IllegalArgumentException("useProvider can't be null"); if (listener == null) throw new IllegalArgumentException("listener can't be null"); if (minTimeFilter < 0) { Log.w(TAG, "minTimeFilter < 0. Setting to 0"); minTimeFilter = 0; } if (minTimeGpsProvider < 0) { Log.w(TAG, "minTimeGpsProvider < 0. Setting to 0"); minTimeGpsProvider = 0; } if (minTimeNetProvider < 0) { Log.w(TAG, "minTimeNetProvider < 0. Setting to 0"); minTimeNetProvider = 0; } // Remove this listener if it is already in use if (mListener2Thread.containsKey(listener)) { Log.d(TAG, "Requested location updates with a listener that is already in use. Removing."); removeUpdates(listener); } LooperThread looperThread = new LooperThread( mContext, useProvider, minTimeFilter, minTimeGpsProvider, minTimeNetProvider, listener, forwardProviderReadings); looperThread.setMaxPredictTime(mMaxPredictTime); mListener2Thread.put(listener, looperThread); }
Example #27
Source File: LocationUpdateService.java From your-local-weather with GNU General Public License v3.0 | 4 votes |
private void removeUpdates(LocationListener locationListener) { String geocoder = AppPreference.getLocationGeocoderSource(this); if("location_geocoder_system".equals(geocoder) || "location_geocoder_local".equals(geocoder)/*TODO: temporary solution*/) { locationManager.removeUpdates(locationListener); } }
Example #28
Source File: SystemLocationService.java From MiBandDecompiled with Apache License 2.0 | 4 votes |
public void registerLocationListener(cn.com.smartdevices.bracelet.location.LocationListener locationlistener) { d = locationlistener; }
Example #29
Source File: LastLocationFinder.java From Android-Next with Apache License 2.0 | 4 votes |
public void setLocationListener(LocationListener li) { locationListener = li; }
Example #30
Source File: InstrumentationService.java From sana.mobile with BSD 3-Clause "New" or "Revised" License | 4 votes |
@SuppressLint("NewApi") public void handleMessage(Message msg) { Log.i(TAG, "msg obj = " + String.valueOf(msg.obj)); switch (msg.what) { case MSG_GET_LOCATION: Uri uri = Uri.parse(msg.obj.toString()); if (msg.getData() != null) { //Intent reply = msg.getData().getParcelable(Intent.EXTRA_INTENT); PendingIntent replyTo = msg.getData().getParcelable(Intent.EXTRA_INTENT); //Log.d(TAG, "replyTo: " + String.valueOf(replyTo)); LocationListener listener = getListener(null, uri, msg.arg1, msg.getData()); try { Criteria criteria = new Criteria(); if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.FROYO) { criteria.setPowerRequirement(Criteria.POWER_HIGH); criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH); } else { criteria.setAccuracy(Criteria.ACCURACY_FINE); } List<String> providers = locationManager.getProviders(criteria, true); for (String provider : providers) { Log.d(TAG, "Using location provider: " + provider); locationManager.requestLocationUpdates(provider, 0, 0, listener); } //if(TextUtils.isEmpty(provider)) // throw new IllegalArgumentException("No location providers available"); // add to our listeners so that we can clean up later if necessary //replies.put(msg.arg1, replyTo); if (providers.size() == 0) { Location nullLocation = new Location(LocationManager.GPS_PROVIDER); nullLocation.setAccuracy(0); nullLocation.setLatitude(0); nullLocation.setLongitude(0); listener.onLocationChanged(nullLocation); } else { listeners.put(msg.arg1, listener); } } catch (Exception e) { Log.e(TAG, "Error getting location updates: " + e.getMessage()); e.printStackTrace(); removeListener(msg.arg1); } } else { Log.w(TAG, "no replyTo in original intent sent to InstrumentationService"); removeListener(msg.arg1); } break; default: Log.w(TAG, "Unknown message! Message = " + msg.what); removeListener(msg.arg1); } }