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 Project: DoraemonKit   Author: didi   File: LocationHooker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @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 #2
Source Project: itag   Author: s4ysolutions   File: HistoryRecord.java    License: GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source Project: mapbox-events-android   Author: mapbox   File: MapboxFusedLocationEngineImpl.java    License: MIT License 6 votes vote down vote up
@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 #4
Source Project: JsBridge   Author: pengwei1024   File: BaseActivity.java    License: Apache License 2.0 6 votes vote down vote up
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 #5
Source Project: sensordatacollector   Author: sztyler   File: GPSCollector.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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 #6
Source Project: PocketMaps   Author: junjunguo   File: LooperThread.java    License: MIT License 6 votes vote down vote up
/**
 *
 * @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 #7
Source Project: JayPS-AndroidApp   Author: team-mount-ventoux   File: GPSServiceCommandTest.java    License: MIT License 6 votes vote down vote up
@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 Project: android_9.0.0_r45   Author: lulululbj   File: LocationBasedCountryDetector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 #9
Source Project: android_9.0.0_r45   Author: lulululbj   File: LocationBasedCountryDetector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unregister an already registered listener
 */
protected void unregisterListener(LocationListener listener) {
    final long bid = Binder.clearCallingIdentity();
    try {
        mLocationManager.removeUpdates(listener);
    } finally {
        Binder.restoreCallingIdentity(bid);
    }
}
 
Example #10
Source Project: android_9.0.0_r45   Author: lulululbj   File: LocationBasedCountryDetector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 #11
Source Project: DevUtils   Author: afkT   File: LocationUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取位置 ( 需要先判断是否开启了定位 )
 * @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 #12
Source Project: itag   Author: s4ysolutions   File: LocationsGPSUpdater.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void cancelLocationUpdates(@NonNull LocationListener listener) {
    if (mLocationManager == null) {
        ErrorsObservable.toast(R.string.no_location_manager);
        return;
    }
    mLocationManager.removeUpdates(listener);
}
 
Example #13
Source Project: AIMSICDL   Author: 5GSD   File: LocationTracker.java    License: GNU General Public License v3.0 5 votes vote down vote up
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 #14
Source Project: mapbox-events-android   Author: mapbox   File: AndroidLocationEngineImpl.java    License: MIT License 5 votes vote down vote up
@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 #15
Source Project: mapbox-events-android   Author: mapbox   File: AndroidLocationEngineImpl.java    License: MIT License 5 votes vote down vote up
@SuppressLint("MissingPermission")
@Override
public void removeLocationUpdates(@NonNull LocationListener listener) {
  if (listener != null) {
    locationManager.removeUpdates(listener);
  }
}
 
Example #16
Source Project: mapbox-events-android   Author: mapbox   File: AndroidLocationEngineImplTest.java    License: MIT License 5 votes vote down vote up
@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 #17
Source Project: mapbox-events-android   Author: mapbox   File: AndroidLocationEngineImplTest.java    License: MIT License 5 votes vote down vote up
@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 Project: mapbox-events-android   Author: mapbox   File: MapboxFusedLocationEngineImplAdditionalTest2.java    License: MIT License 5 votes vote down vote up
@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 #19
Source Project: mapbox-events-android   Author: mapbox   File: LocationEngineProxyTest.java    License: MIT License 5 votes vote down vote up
@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 #20
Source Project: mapbox-events-android   Author: mapbox   File: MapboxFusedLocationEngineImplTest.java    License: MIT License 5 votes vote down vote up
@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 #21
Source Project: mapbox-events-android   Author: mapbox   File: MapboxFusedLocationEngineImplTest.java    License: MIT License 5 votes vote down vote up
@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 #22
Source Project: mapbox-events-android   Author: mapbox   File: MapboxFusedLocationEngineImplTest.java    License: MIT License 5 votes vote down vote up
@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 #23
Source Project: osmdroid   Author: osmdroid   File: LocationListenerProxy.java    License: Apache License 2.0 5 votes vote down vote up
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 #24
Source Project: JayPS-AndroidApp   Author: team-mount-ventoux   File: GPSServiceCommandTest.java    License: MIT License 5 votes vote down vote up
@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 #25
Source Project: JayPS-AndroidApp   Author: team-mount-ventoux   File: GPSServiceCommandTest.java    License: MIT License 5 votes vote down vote up
@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 #26
Source Project: DoraemonKit   Author: didi   File: LocationHooker.java    License: Apache License 2.0 4 votes vote down vote up
private LocationListenerProxy(LocationListener locationListener) {
    this.locationListener = locationListener;
}
 
Example #27
Source Project: your-local-weather   Author: thuryn   File: LocationUpdateService.java    License: GNU General Public License v3.0 4 votes vote down vote up
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 Project: itag   Author: s4ysolutions   File: LocationsUpdater.java    License: GNU General Public License v3.0 4 votes vote down vote up
void requestLocationUpdates(
@NonNull LocationListener locationListener,
@NonNull RequestUpdatesListener requestListener,
int frequency);
 
Example #29
Source Project: ridesharing-android   Author: hypertrack   File: MapViewsPresenter.java    License: MIT License 4 votes vote down vote up
public void setLocationUpdatesListener(LocationListener locationListener) {
    if (hyperTrackMap != null) {
        hyperTrackMap.setLocationUpdatesListener(locationListener);
    }
}
 
Example #30
Source Project: mapbox-events-android   Author: mapbox   File: AndroidLocationEngineImpl.java    License: MIT License 4 votes vote down vote up
@NonNull
@Override
public LocationListener createListener(LocationEngineCallback<LocationEngineResult> callback) {
  return new AndroidLocationEngineCallbackTransport(callback);
}