/** * Get the current location of the device * ref: https://chantisandroid.blogspot.ca/2017/06/get-current-location-example-in-android.html * @return current location */ private Location getDeviceLoc() { if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission (MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION); } else { Location location = service.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); Location location1 = service.getLastKnownLocation(LocationManager.GPS_PROVIDER); Location location2 = service.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); if (location != null) { return location; } else if (location1 != null) { return location1; } else if (location2 != null) { return location2; } else { Toast.makeText(this, "Unable to trace your location", Toast.LENGTH_SHORT).show(); } } return null; }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { Toast.makeText(this, R.string.bt_on, Toast.LENGTH_SHORT).show(); } else { // User did not enable Bluetooth or an error occurred Toast.makeText(this, R.string.bt_not_on, Toast.LENGTH_SHORT).show(); finish(); } break; case REQUEST_ENABLE_LOCATION: if (isLocationProviderEnabled((LocationManager) getSystemService(Context.LOCATION_SERVICE))) { initBluManager(); } break; default: Log.e(TAG, "Unknown request code"); break; } }
@Override public void onLocationChanged(Location location) { map.setOnMapLoadedCallback(this); this.location = location; if(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) != null) { mystringLatitude = String.valueOf(getLatitude()); mystringLongitude = String.valueOf(getLongitude()); // Toast.makeText(this,"Activity OLC Update " + networkTS,Toast.LENGTH_SHORT).show(); } this.location = location; Latitude = String.valueOf(getLatitude()); Longitude = String.valueOf(getLongitude()); }
@Override protected void onActive() { if (ActivityCompat.checkSelfPermission(context, permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, 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. return; } locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener); }
@Override public void onCreate() { hasAltitude = false; hasVelocity = false; hasAcceleration = false; listenerStarted = false; hasBearing = false; hasDistance = false; mLocation = null; callbacks = new ArrayList<>(); mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // send start broadcast Intent startIntent = new Intent(); startIntent.setAction(SERVICE_START); sendBroadcast(startIntent); }
@Override public Object call(Object who, Method method, Object... args) throws Throwable { if (isFakeLocationEnable()) { Object transport = ArrayUtils.getFirst(args, mirror.android.location.LocationManager.GpsStatusListenerTransport.TYPE); Object locationManager = mirror.android.location.LocationManager.GpsStatusListenerTransport.this$0.get(transport); mirror.android.location.LocationManager.GpsStatusListenerTransport.onGpsStarted.call(transport); mirror.android.location.LocationManager.GpsStatusListenerTransport.onFirstFix.call(transport, 0); if (mirror.android.location.LocationManager.GpsStatusListenerTransport.mListener.get(transport) != null) { MockLocationHelper.invokeSvStatusChanged(transport); } else { MockLocationHelper.invokeNmeaReceived(transport); } GPSListenerThread.get().addListenerTransport(locationManager); return true; } return super.call(who, method, args); }
/** * 注册 * <p>使用完记得调用{@link #unregister()}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>}</p> * <p>如果{@code minDistance}为0,则通过{@code minTime}来定时更新;</p> * <p>{@code minDistance}不为0,则以{@code minDistance}为准;</p> * <p>两者都为0,则随时刷新。</p> * * @param minTime 位置信息更新周期(单位:毫秒) * @param minDistance 位置变化最小距离:当位置距离变化超过此值时,将更新位置信息(单位:米) * @param listener 位置刷新的回调接口 * @return {@code true}: 初始化成功<br>{@code false}: 初始化失败 */ public static boolean register(long minTime, long minDistance, OnLocationChangeListener listener) { if (listener == null) return false; mLocationManager = (LocationManager) Utils.getContext().getSystemService(Context.LOCATION_SERVICE); mListener = listener; if (!isLocationEnabled()) { ToastUtils.showShortSafe("无法定位,请打开定位服务"); return false; } String provider = mLocationManager.getBestProvider(getCriteria(), true); Location location = mLocationManager.getLastKnownLocation(provider); if (location != null) listener.getLastKnownLocation(location); if (myLocationListener == null) myLocationListener = new MyLocationListener(); mLocationManager.requestLocationUpdates(provider, minTime, minDistance, myLocationListener); return true; }
public BLEClient.BtError checkBluetooth(){ btManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); btAdapter = btManager.getAdapter(); if(!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) return BLEClient.BtError.NoBluetooth; if(!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) return BLEClient.BtError.NoBLE; if(btAdapter == null || !btAdapter.isEnabled()) return BLEClient.BtError.Disabled; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && useNewMethod){ if((ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) && (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED)){ return BtError.NoLocationPermission; } LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); if(!(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) && !(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))){ return BtError.LocationDisabled; } } return BLEClient.BtError.None; }
/** * 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); } } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textOut = (TextView) findViewById(R.id.textOut); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); // <5> geocoder = new Geocoder(this); // <6> // Initialize with the last known location Location lastLocation = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); // <7> if (lastLocation != null) onLocationChanged(lastLocation); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { final int minTime = (int) TimeUnit.MINUTES.toMillis(4); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime, 150, this); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, 150, this); if (intent.getAction() != null) { if (intent.getAction().equals(GEOCODE_ON_ACTION)) mustGeocode = true; else if (intent.getAction().equals(GEOCODE_OFF_ACTION)) mustGeocode = false; } sendLocalBroadcastIntent(getBestLastKnownLocation(this)); } return START_REDELIVER_INTENT; }
@Override public Object call(final Object who, Method method, Object... args) throws Throwable { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) { LocationRequest request = (LocationRequest) args[0]; fixLocationRequest(request); } if (isFakeLocationEnable()) { Object transport = ArrayUtils.getFirst(args, mirror.android.location.LocationManager.ListenerTransport.TYPE); if (transport != null) { Object locationManager = mirror.android.location.LocationManager.ListenerTransport.this$0.get(transport); MockLocationHelper.setGpsStatus(locationManager); GPSListenerThread.get().addListenerTransport(locationManager); } return 0; } return super.call(who, method, args); }
private void registerProvidersChangedReceiver(Context broadcastContext) { receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.i(TAG, "registerProvidersChangedReceiver, action: " + action); if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(action)) { start(); } } }; if (receiver != null && broadcastContext != null) { IntentFilter filter = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION); broadcastContext.registerReceiver(receiver, filter); } }
public Location getLocation() { if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(context, "Permission not granted", Toast.LENGTH_SHORT).show(); return null; } LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); if (isGPSEnabled) { lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10, this); Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); return l; } else { Toast.makeText(context, "Please enable GPS !", Toast.LENGTH_LONG).show(); } return null; }
/** * Adds the user's current location the the habit event * * @param view View */ public void attachLocation(View view) { // boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER); // if (!enabled) { // Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); // startActivity(intent); // } else { // getDeviceLoc(); // } locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { buildAlertMessageNoGps(); } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { try { location = getDeviceLoc(); Toast.makeText(this,"Location Attached",Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this,"Unable to trace your location",Toast.LENGTH_SHORT).show(); } } }
@Override protected void onPreExecute() { Log.d(TAG, "Trying to determine location..."); locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); locationListener = new BackgroundLocationListener(); try { if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { // Only uses 'network' location, as asking the GPS every time would drain too much battery locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } else { Log.d(TAG, "'Network' location is not enabled. Cancelling determining location."); onPostExecute(null); } } catch (SecurityException e) { Log.e(TAG, "Couldn't request location updates. Probably this is an Android (>M) runtime permissions issue ", e); } }
public static String getLocation(Context context) { if (context == null) { return ""; } try { LocationManager locationManager = (LocationManager) context.getSystemService(HOME_RECOMMEND_PARAMETERS.LOCATION); Criteria criteria = new Criteria(); criteria.setCostAllowed(false); criteria.setAccuracy(2); String bestProvider = locationManager.getBestProvider(criteria, true); if (bestProvider != null) { Location lastKnownLocation = locationManager.getLastKnownLocation(bestProvider); if (lastKnownLocation == null) { return ""; } double latitude = lastKnownLocation.getLatitude(); g = latitude + "*" + lastKnownLocation.getLongitude(); return g; } } catch (Throwable e) { f.b("getLocation", "getLocation>>>", e); } return ""; }
@Override @SuppressWarnings({"MissingPermission"}) protected void onResume() { super.onResume(); //if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //especificando GPS_PROVIDER //atualizacoes de hora em hora //o dispositivo deve ter se movido em pelo menos 1km //objeto LocationListener //mgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3600000, 1000, this); //se colocar 0,0 tenta o maximo de updates mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, this); //pode usar com PendingIntent, para disparar um broadcast por ex. //addProximityAlert() //} }
private void findStationNearly() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Sur Défaut, l'on force la localisation de "FDF - Lycée Bellevue" stationMadininair= new StationsMadininair(14.602902, 61.077537); tvStationNearly.setText(R.string.find_station_error); } else { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //TODO: a controler si cela fonctionne avec d'autres périphériques Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); stationMadininair= new StationsMadininair(loc.getLatitude(), loc.getLongitude()); tvStationNearly.setText(String.format("%s : %s", getString(R.string.display_station_nearly), Utilites.recupNomStation(stationMadininair.getNumStationNearly()))); } }
/** * 注册 * <p>使用完记得调用{@link #unregister()}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>}</p> * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>}</p> * <p>如果{@code minDistance}为0,则通过{@code minTime}来定时更新;</p> * <p>{@code minDistance}不为0,则以{@code minDistance}为准;</p> * <p>两者都为0,则随时刷新。</p> * * @param minTime 位置信息更新周期(单位:毫秒) * @param minDistance 位置变化最小距离:当位置距离变化超过此值时,将更新位置信息(单位:米) * @param listener 位置刷新的回调接口 * @return {@code true}: 初始化成功<br>{@code false}: 初始化失败 */ public static boolean register(long minTime, long minDistance, OnLocationChangeListener listener) { if (listener == null) return false; mLocationManager = (LocationManager) Utils.getContext().getSystemService(Context.LOCATION_SERVICE); mListener = listener; if (!isLocationEnabled()) { ToastUtils.showShortToastSafe("无法定位,请打开定位服务"); return false; } String provider = mLocationManager.getBestProvider(getCriteria(), true); Location location = mLocationManager.getLastKnownLocation(provider); if (location != null) listener.getLastKnownLocation(location); if (myLocationListener == null) myLocationListener = new MyLocationListener(); mLocationManager.requestLocationUpdates(provider, minTime, minDistance, myLocationListener); return true; }
@Test public void checksSendEventNotCalledWhenNegativeInfiniteLatitude() throws Exception { Context mockedContext = mock(Context.class); Intent mockedIntent = mock(Intent.class); when(mockedIntent.getStringExtra(eq("location_received"))).thenReturn("onLocation"); Bundle mockedBundle = mock(Bundle.class); when(mockedIntent.getExtras()).thenReturn(mockedBundle); Location mockedLocation = mock(Location.class); when(mockedBundle.get(eq(LocationManager.KEY_LOCATION_CHANGED))).thenReturn(mockedLocation); when(mockedLocation.getLatitude()).thenReturn(Double.NEGATIVE_INFINITY); EventSender mockedEventSender = mock(EventSender.class); LocationReceiver theLocationReceiver = new LocationReceiver(mockedEventSender); theLocationReceiver.onReceive(mockedContext, mockedIntent); verify(mockedEventSender, never()).send(any(LocationEvent.class)); }
@Override public ControllerParent<GpsShield> init(String tag) { mLocationClient = new GoogleApiClient.Builder(getApplication()) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mUpdatesRequested = false; manager = (LocationManager) getApplication().getSystemService( Context.LOCATION_SERVICE); // check if Google play services available, no dialog displayed if (isGoogleplayServicesAvailableNoDialogs()) { if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) startGps(); } return super.init(tag); }
/** * @return the location this event occurred at if it exists, or null otherwise */ public Location getLocation() { if (latitude == INVALID_LATLONG) return null; Location location = new Location(LocationManager.GPS_PROVIDER); location.setLatitude(latitude); location.setLongitude(longitude); return location; }
public static String getProvider(Context ctx, LocationManager mLocationManager) { String mProviderName = ""; if (isNetworkConnected(ctx)) { boolean hasGpsProvide; boolean hasNetWorkProvider; if (mLocationManager.getProvider("gps") != null) { hasGpsProvide = true; } else { hasGpsProvide = false; } if (mLocationManager.getProvider("network") != null) { hasNetWorkProvider = true; } else { hasNetWorkProvider = false; } Helper.showLog(TAG, " hasGpsProvide =" + hasGpsProvide + " hasNetWorkProvider =" + hasNetWorkProvider); boolean isGpsEnabled = isGPSProviderAvaliable(ctx); boolean isWIFIEnabled = isWIFIProviderAvaliable(ctx); if (!hasGpsProvide && !hasNetWorkProvider) { Helper.showToast(ctx, (int) R.string.xw); return ctx.getString(R.string.xw); } else if (!hasGpsProvide && hasNetWorkProvider) { Helper.showLog(TAG, ">>>>>>>>>>>>>>>only network provider"); if (isWIFIEnabled) { mProviderName = "network"; } else { Helper.showLog(TAG, ">>>>>>>>>>>>>>>no network avaliable"); return null; } } else if (!hasGpsProvide || hasNetWorkProvider) { Helper.showLog(TAG, ">>>>>>>>>>>>>>>hasallprovider"); if (!isGpsEnabled && !isWIFIEnabled) { Helper.showLog(TAG, ">>>>>>>>>>>>>>>no GPS or NETWORK avaliable"); return null; } else if (isGpsEnabled && !isWIFIEnabled) { mProviderName = "gps"; } else if (!isGpsEnabled && isWIFIEnabled) { Helper.showLog(TAG, ">>>>>>>>>>>>>>>network avaliable"); mProviderName = "network"; } else if (isGpsEnabled && isWIFIEnabled) { Helper.showLog(TAG, ">>>>>>>>>>>>>>>all avaliable"); mProviderName = "gps"; if (mLocationManager.getLastKnownLocation("gps") == null) { Helper.showLog(TAG, ">>>>>>>>>>>>>>>all avaliable but location is null"); mProviderName = "network"; } } } else { Helper.showLog(TAG, ">>>>>>>>>>>>>>>only GPS provider"); if (isGpsEnabled) { mProviderName = "gps"; } else { Helper.showLog(TAG, ">>>>>>>>>>>>>>>no GPS avaliable"); return null; } } } Helper.showToast(ctx, ctx.getString(R.string.gu)); return mProviderName; }
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 ); }
/** * des:提示开启GPS */ private void initGPS() { LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); // 判断GPS模块是否开启,如果没有则跳转至设置开启界面,设置完毕后返回到首页 if (!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("GPS提示:"); builder.setMessage("请打开GPS开关,以便您更准确的找到自行车"); builder.setCancelable(true); builder.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { // 转到手机设置界面,用户设置GPS Intent intent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent, 2); // 设置完成后返回到原来的界面 } }); builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } }
void statusUpdate() { date = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime(); networkTS = sdf.format(date); Latitude = String.valueOf(getLatitude()); Longitude = String.valueOf(getLongitude()); InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); String status = edttxt.getText().toString(); ConnectionDetector cd = new ConnectionDetector(getApplicationContext()); Boolean isInternetPresent = cd.isConnectingToInternet(); if(isInternetPresent) { try { web.loadUrl("http://skylinelabs.in/Geo/status.php?user_name=" + mydevice_id + "&latitude=" + Latitude + "&longitude=" + Longitude + "&time=" + sdf.format(date) + "&status=" + status); } catch (Exception e) { } } else { //Toast.makeText(this, "Please connect to internet", Toast.LENGTH_SHORT).show(); Snackbar.make(findViewById(android.R.id.content), "Please connect to internet", Snackbar.LENGTH_LONG) .setAction("Ok", snackaction) .setActionTextColor(Color.WHITE) .show(); } }
@Rubric( value = "testCorrectLoc()", goal = "Test if Service stores the correct location for an entry.", points = 10.0, reference = { } ) @Test public void testCorrectLoc() throws TimeoutException{ sendToService(TEST_DESC_1); Cursor cur = mDB.queryEntries(null, null, null, TEST_DESC_1); cur.moveToFirst(); LocationManager locationManager = (LocationManager) InstrumentationRegistry.getTargetContext() .getSystemService(LOCATION_SERVICE); String lat = null; String lon = null; Location location = getLastKnownLocation(); if (location != null) { lat = String.valueOf(location.getLatitude()); lon = String.valueOf(location.getLongitude()); } else { lat = LOCATION_UNKNOWN; lon = LOCATION_UNKNOWN; } assertEquals(lat, cur.getString(cur.getColumnIndex(LocDBContract.FeedEntry.COLUMN_NAME_ENTRY_LATITUDE))); assertEquals(lon, cur.getString(cur.getColumnIndex(LocDBContract.FeedEntry.COLUMN_NAME_ENTRY_lONGITUDE))); resetDB(); }
@Inject public RawGPSNavigationGatherer(SensorConfig sensorConfig, LocationManager locationManager, @Named("gpsSensorEnableRequester") SensorEnableRequester sensorEnableRequester, @Named("fineLocationPermissionChecker") PermissionChecker permissionChecker, @Named("rawGPSSensorChecker") SensorChecker sensorChecker, SensorRequirementChecker sensorRequirementChecker) { super(sensorConfig, locationManager, sensorEnableRequester, permissionChecker, sensorChecker, sensorRequirementChecker); }
@Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); // Init some singletons which need the Context Analytics.getInstance().init(this); SettingsUtils.getInstance().init(this); // Get the location manager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); }
/** * Stop listening for location updates. * * NB: this is not balanced with {@link #startObserving}: any number of calls to that method will * be canceled by just one call to this one. */ @ReactMethod public void stopObserving() { LocationManager locationManager = (LocationManager) getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE); locationManager.removeUpdates(mLocationListener); mWatchedProvider = null; }
/** * Callback on provider disabled * @param provider Provider */ @Override public void onProviderDisabled(String provider) { if (Logger.DEBUG) { Log.d(TAG, "[location provider " + provider + " disabled]"); } if (provider.equals(LocationManager.GPS_PROVIDER)) { sendBroadcast(BROADCAST_LOCATION_GPS_DISABLED); } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) { sendBroadcast(BROADCAST_LOCATION_NETWORK_DISABLED); } }
public void attachUpdatedLocation(View view) { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { buildAlertMessageNoGps(); } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { try { location = getDeviceLoc(); Toast.makeText(this,"Location Updated",Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this,"Unable to trace your location",Toast.LENGTH_SHORT).show(); } } }
public SystemSetting(ReactApplicationContext reactContext) { super(reactContext); mContext = reactContext; am = (AudioManager) getReactApplicationContext().getApplicationContext().getSystemService(Context.AUDIO_SERVICE); wm = (WifiManager) getReactApplicationContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE); lm = (LocationManager) getReactApplicationContext().getApplicationContext().getSystemService(Context.LOCATION_SERVICE); listenVolume(reactContext); }
/** * A custom Threshold example for geofencing */ public GeoFenceThreshold(boolean required, Context context, Location locationNear, float distanceLimit) { super (required); this.context = context; this.locationNear = locationNear; this.distanceLimit = distanceLimit; locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); }
@Override public Object call(Object who, Method method, Object... args) throws Throwable { if (isFakeLocationEnable()) { return LocationManager.GPS_PROVIDER; } return super.call(who, method, args); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); localM = (LocationManager) getSystemService(Context.LOCATION_SERVICE); myProvider = localM.getBestProvider(new Criteria(), false); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } myLocation = localM.getLastKnownLocation(myProvider); if (myLocation != null) { Log.i("WJH", myLocation.toString()); } else { Log.i("WJH", "Location is null."); } }
private void check(CallbackContext callbackContext){ Context context = this.cordova.getActivity().getApplicationContext(); final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE ); if ( manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) { callbackContext.success(); }else{ callbackContext.error(0); } }
public Location getLocation() { try { locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); } } } if (isNetworkEnabled) { if (location == null) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } } } } } catch (Exception e) { e.printStackTrace(); } return location; }