List of usage examples for android.location LocationListener LocationListener
LocationListener
From source file:com.esri.squadleader.controller.LocationController.java
@Override protected LocationProvider createLocationServiceProvider() { return new LocationProvider() { private LocationListener locationListener = new LocationListener() { @Override// w w w .j a v a 2 s.com public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(android.location.Location location) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(location.getTime()); Location theLocation = new Location(location.getLongitude(), location.getLatitude(), cal, location.getSpeed(), location.getBearing()); sendLocation(theLocation); } }; private LocationProviderState state = LocationProviderState.STOPPED; @Override public void start() { setupLocationListener(); if (null == targetActivity) { Log.w(TAG, "targetActivity is null, which means LocationController won't use the device's location capabilities."); } else if (ContextCompat.checkSelfPermission(targetActivity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { switch (getState()) { case PAUSED: { if (null != locationDisplayManager) { locationDisplayManager.resume(); } break; } case STOPPED: { if (null != locationDisplayManager) { locationDisplayManager.start(); } break; } case STARTED: default: { } } state = LocationProviderState.STARTED; } } @Override public void pause() { if (LocationProviderState.STARTED == state) { if (null != locationDisplayManager) { locationDisplayManager.pause(); } state = LocationProviderState.PAUSED; } } @Override public void stop() { if (null != locationDisplayManager) { locationDisplayManager.stop(); } state = LocationProviderState.STOPPED; } @Override public LocationProviderState getState() { return state; } private void setupLocationListener() { if (null != locationDisplayManager) { locationDisplayManager.setLocationListener(locationListener); } } }; }
From source file:com.caju.uheer.app.services.infrastructure.ContactablesLoaderCallbacks.java
@Override public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) { final ArrayList<String> infoAndName = new ArrayList<String>(); try {/*from www . j a v a 2s.co m*/ for (int i = 0; i < usersFound.length(); i++) { infoAndName.add(usersFound.getJSONObject(i).getString("name")); } } catch (JSONException e) { e.printStackTrace(); } LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { Location geoPointLocation = new Location("geoPoint"); try { infoAndName.clear(); for (int i = 0; i < usersFound.length(); i++) { String appendedText = ""; if (!usersFound.getJSONObject(i).has("channel")) { geoPointLocation.setLongitude(usersFound.getJSONObject(i).getDouble("lon")); geoPointLocation.setLatitude(usersFound.getJSONObject(i).getDouble("lat")); float distance = location.distanceTo(geoPointLocation) / 1000; appendedText = String.format("%.1f", distance) + "Km"; } else { appendedText = usersFound.getJSONObject(i).getString("channel"); } infoAndName.add(appendedText + usersFound.getJSONObject(i).getString("name")); Log.e("infoandname", infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1)); Toast.makeText(mContext, infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1), Toast.LENGTH_LONG).show(); // infoAndName tem a informacao de distancia ou canal e o nome. Precisa editar //essa parte de baixo pra usar o infoAndName. ArrayList<String> friendsEmails = new ArrayList<>(); friendsEmails.addAll(infoAndName); friendsEmails = new ArrayList<>(); for (ArrayList<String> array : ServerInformation.getAllActiveListeners()) { friendsEmails.addAll(array); while (friendsEmails.contains(connectedEmail)) friendsEmails.remove(connectedEmail); } EmailListAdapter listAdapter = new EmailListAdapter(mContext, R.layout.adapter_email_list, friendsEmails); ListView emails = (ListView) ((Activity) mContext) .findViewById(R.id.gps_friends_from_drawer); emails.setAdapter(listAdapter); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; // Minimum of 2 minutes between checks (120000 milisecs). locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 120000, 0, locationListener); }
From source file:de.htw.ar.treasurehuntar.AbstractArchitectActivity.java
/** * Called when the activity is first created. *//*w w w. j ava 2 s.c om*/ @SuppressLint("NewApi") @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); // pressing volume up/down should cause music volume changes this.setVolumeControlStream(AudioManager.STREAM_MUSIC); this.setContentView(this.getContentViewId()); this.setTitle(this.getActivityTitle()); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Log.i("architect", "create"); mGestureDetector = createGestureDetector(this); // // this enables remote debugging of a WebView on Android 4.4+ when debugging = true in AndroidManifest.xml // If you get a compile time error here, ensure to have SDK 19+ used in your ADT/Eclipse. // You may even delete this block in case you don't need remote debugging or don't have an Android 4.4+ device in place. // Details: https://developers.google.com/chrome-developer-tools/docs/remote-debugging // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) { WebView.setWebContentsDebuggingEnabled(true); } } // set AR-view for life-cycle notifications etc. this.architectView = (ArchitectView) this.findViewById(this.getArchitectViewId()); // pass SDK key if you have one, this one is only valid for this package identifier and must not be used somewhere else final ArchitectConfig config = new ArchitectConfig(this.getWikitudeSDKLicenseKey()); try { // first mandatory life-cycle notification this.architectView.onCreate(config); } catch (RuntimeException rex) { this.architectView = null; Toast.makeText(getApplicationContext(), "can't create Architect View", Toast.LENGTH_SHORT).show(); Log.e(this.getClass().getName(), "Exception in ArchitectView.onCreate()", rex); } // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener this.sensorAccuracyListener = this.getSensorAccuracyListener(); // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment this.urlListener = this.getUrlListener(); // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event if (this.urlListener != null && this.architectView != null) { this.architectView.registerUrlListener(this.getUrlListener()); } // listener passed over to locationProvider, any location update is handled here this.locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(final Location location) { // forward location updates fired by LocationProvider to architectView, you can set lat/lon from any location-strategy if (location != null) { Log.i("location", location.toString()); // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project) AbstractArchitectActivity.this.lastKnownLocation = location; if (AbstractArchitectActivity.this.architectView != null) { // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information) if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) { AbstractArchitectActivity.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy()); } else { AbstractArchitectActivity.this.architectView.setLocation(location.getLatitude(), location.getLongitude(), location.hasAccuracy() ? location.getAccuracy() : 1000); } } } } }; // locationProvider used to fetch user position this.locationProvider = new LocationProvider(this, this.locationListener); }
From source file:com.warp10.app.LocationService.java
/** * Handler of action Start/*from www .j a v a2 s.com*/ * @param isListenGPS if asked register GPS * @param isListenNetWork if asked register Network location */ private void handleActionStart(boolean isListenGPS, boolean isListenNetWork, final Context context, boolean recGPS, boolean recNetwork, final String prefixGTS) { // Define a listener that responds to location updates if (isRunning) { this.onDestroy(); } locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); final boolean record = recGPS || recNetwork; locationListener = new LocationListener() { public void onLocationChanged(Location location) { if (record) { //Log.d("GPSLOCA",location.toString()); long timestamp = System.currentTimeMillis() * 1000; // If buffer have full size if (null == stringBuffer) { stringBuffer = new StringBuffer(); } if (stringBuffer.length() >= BUFFER_SIZE) { emptyBuffer(); } if (stringBuffer.length() > 0) { stringBuffer.append("\n"); } String fix = ""; /** if(prefixGTS.equals(new String())) { prefixGTS = "android"; }*/ if (prefixGTS.length() != prefixGTS.lastIndexOf(".")) { fix = "."; } String string = timestamp + "/" + location.getLatitude() + ":" + location.getLongitude() + "/ " + prefixGTS + fix + location.getProvider() + "{" + "source=android" + "} true"; stringBuffer.append(string); //Log.d("Location Handler", stringBuffer.toString()); } } public void onStatusChanged(String provider, int status, Bundle extras) { //emptyBuffer(); } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { emptyBuffer(); } /** * empty current buffer */ public void emptyBuffer() { if (null != stringBuffer) { //Log.d("LocationService", stringBuffer.toString()); final StringBuffer buffer = new StringBuffer(stringBuffer); if (CollectService.isPostActive) { FileService.writeToFile(buffer.toString(), context); } else { if (CollectService.ws.isClosed()) { FileService.writeToFile(buffer.toString(), context); } else { List<File> allFiles = FileService.getAllFiles("fill", context, true); for (File file : allFiles) { String data = FileService.readMetricFile(file); if (CollectService.ws.writeData(data)) { file.delete(); } } if (!CollectService.ws.writeData(buffer.toString())) { FileService.writeToFile(buffer.toString(), context); } } } stringBuffer = new StringBuffer(); } } }; // Register the listener with the Location Manager to receive location updates if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } if (isListenGPS || recGPS) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, locationListener); setLocManager(); } if (isListenNetWork || recNetwork) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, locationListener); setLocManager(); } //Log.d("LOCATIONB", locationManager.getAllProviders().toString()); //Log.d("LOCATIONB", locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).toString()); isRunning = true; }
From source file:com.example.scrumptious.PickerActivity.java
@Override protected void onStart() { super.onStart(); if (FRIEND_PICKER.equals(getIntent().getData())) { try {// w ww . j a v a 2 s.c o m friendPickerFragment.loadData(false); } catch (Exception ex) { onError(ex); } } else if (PLACE_PICKER.equals(getIntent().getData())) { try { Location location = null; Criteria criteria = new Criteria(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String bestProvider = locationManager.getBestProvider(criteria, false); if (bestProvider != null) { location = locationManager.getLastKnownLocation(bestProvider); if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { boolean updateLocation = true; Location prevLocation = placePickerFragment.getLocation(); if (prevLocation != null) { updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD; } if (updateLocation) { placePickerFragment.setLocation(location); placePickerFragment.loadData(true); } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD, locationListener, Looper.getMainLooper()); } } if (location != null) { placePickerFragment.setLocation(location); placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS); placePickerFragment.setSearchText(SEARCH_TEXT); placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT); placePickerFragment.loadData(false); } } catch (Exception ex) { onError(ex); } } }
From source file:com.example.vedantn.algaeestimator.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Set values for the main spinner calcMethodSpinner = (Spinner) findViewById(R.id.calcMethodSpinner); ArrayAdapter adapterCalcMethod = ArrayAdapter.createFromResource(this, R.array.calcMethod, android.R.layout.simple_spinner_dropdown_item); calcMethodSpinner.setAdapter(adapterCalcMethod); calcMethodSpinner.setOnItemSelectedListener(this); spinnerDepth = (Spinner) findViewById(R.id.spinnerDepth); spinnerDepth.setOnItemSelectedListener(this); spinnerStemp = (Spinner) findViewById(R.id.spinnerStemp); spinnerStemp.setOnItemSelectedListener(this); spinnerBotTemp = (Spinner) findViewById(R.id.spinnerBotTemp); spinnerBotTemp.setOnItemSelectedListener(this); spinnerSD = (Spinner) findViewById(R.id.spinnerSD); spinnerSD.setOnItemSelectedListener(this); //Get all user inputs tbValueOfAlgal = (EditText) findViewById(R.id.tbValueOfAlgal); tbPbott = (EditText) findViewById(R.id.tbPbott); tbDepth = (EditText) findViewById(R.id.tbDepth); tbStemp = (EditText) findViewById(R.id.tbStemp); tbBotTemp = (EditText) findViewById(R.id.tbBotTemp); tbSD = (EditText) findViewById(R.id.tbSD); tbDO = (EditText) findViewById(R.id.tbDO); tbLakeDescription = (EditText) findViewById(R.id.tbLakeDescription); lblLocation = (TextView) findViewById(R.id.lblLocation); //Get GPS coordinates locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override//from w ww .ja va2 s . c o m //This methods is called every time the GPS location changes public void onLocationChanged(Location location) { if (location != null) { userLat = location.getLatitude(); userLon = location.getLongitude(); //Toast.makeText(MainActivity.this,"Location Changed",Toast.LENGTH_LONG).show(); lblLocation.setText("Current Location\n" + userLat + "\n" + userLon); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; //Get location updated after 60000 milliseconds or 5 meters. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 5, locationListener); }
From source file:com.eutectoid.dosomething.PickerActivity.java
@Override protected void onStart() { super.onStart(); if (FRIEND_PICKER.equals(getIntent().getData())) { try {/* w ww . ja va 2s. c om*/ friendPickerFragment.loadData(false); } catch (Exception ex) { onError(ex); } } else if (PLACE_PICKER.equals(getIntent().getData())) { try { Location location = null; Criteria criteria = new Criteria(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String bestProvider = locationManager.getBestProvider(criteria, false); // API 23: we have to check if ACCESS_FINE_LOCATION and/or ACCESS_COARSE_LOCATION permission are granted if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { location = locationManager.getLastKnownLocation(bestProvider); if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) { locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { boolean updateLocation = true; Location prevLocation = placePickerFragment.getLocation(); if (prevLocation != null) { updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD; } if (updateLocation) { placePickerFragment.setLocation(location); placePickerFragment.loadData(true); } } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD, locationListener, Looper.getMainLooper()); } } if (location != null) { placePickerFragment.setLocation(location); placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS); placePickerFragment.setSearchText(SEARCH_TEXT); placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT); placePickerFragment.loadData(false); } } catch (Exception ex) { onError(ex); } } }
From source file:com.esri.android.rt.map.MapsApp.java
/** Called when the activity is first created. */ @Override/*from www .j a v a 2 s. c om*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Retrieve the map and initial extent from recreation webmap recWebMapURL = getString(R.string.rec_webmap_url); mMapView = new MapView(this, recWebMapURL, "", ""); // set the content view to the map // setContentView(mMapView); setMapView(mMapView); // attribute app and pan across dateline addAttributes(); // Zoom to device location and accept intent from route layout mMapView.setOnStatusChangedListener(new OnStatusChangedListener() { private static final long serialVersionUID = 1L; @Override public void onStatusChanged(Object source, STATUS status) { if (source == mMapView && status == STATUS.INITIALIZED) { // add search and routing layers addGraphicLayers(); // start location service LocationService ls = mMapView.getLocationService(); ls.setAutoPan(false); ls.setLocationListener(new LocationListener() { boolean locationChanged = false; // Zooms to the current location when first GPS fix // arrives. @Override public void onLocationChanged(Location loc) { if (!locationChanged) { locationChanged = true; double locy = loc.getLatitude(); double locx = loc.getLongitude(); Point wgspoint = new Point(locx, locy); mLocation = (Point) GeometryEngine.project(wgspoint, SpatialReference.create(4326), mMapView.getSpatialReference()); Unit mapUnit = mMapView.getSpatialReference().getUnit(); double zoomWidth = Unit.convertUnits(SEARCH_RADIUS, Unit.create(LinearUnit.Code.MILE_US), mapUnit); Envelope zoomExtent = new Envelope(mLocation, zoomWidth, zoomWidth); mMapView.setExtent(zoomExtent); extras = getIntent().getExtras(); if (extras != null) { startText = extras.getString("start"); endText = extras.getString("end"); basemap = extras.getInt("basemap"); // route start and end points route(startText, endText); } } } @Override public void onProviderDisabled(String arg0) { } @Override public void onProviderEnabled(String arg0) { } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { } }); ls.start(); } } }); mMapView.setOnLongPressListener(new OnLongPressListener() { private static final long serialVersionUID = 1L; @Override public void onLongPress(float x, float y) { Point mapPoint = mMapView.toMapPoint(x, y); new ReverseGeocoding(MapsApp.this, mMapView).execute(mapPoint); } }); }
From source file:com.johan.vertretungsplan_2.SelectSchoolActivity.java
private void showListGeo() { final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); // no GPS final String provider = locationManager.getBestProvider(criteria, true); if (provider == null) { Log.d("vertretungsplan", "provider==null"); tvLocateString.setText(R.string.geolocate_disabled); status = Status.LIST;/* w w w . j ava 2s.c o m*/ return; } locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { if (!visible) return; if (location != null) { double lat = location.getLatitude(); double lon = location.getLongitude(); for (Schule school : schools) { float[] result = new float[1]; Location.distanceBetween(lat, lon, school.getGeo()[0], school.getGeo()[1], result); school.setDistance(result[0]); Log.d("vertretungsplan", school.getName() + ": " + school.getDistance()); } Collections.sort(schools, new DistanceSchoolComparator()); lstSchools.setAdapter(new SchoolsAdapter(SelectSchoolActivity.this, schools, true)); } tvLocateString.setText(R.string.alphabetic_list); ivLocationIcon.setImageResource(R.drawable.ic_action_view_as_list); status = Status.GEO; } }); }
From source file:com.davidmascharka.lips.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestMyPermissions();//from www . j ava 2 s . c om } getPreferences(); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit(); } rotation = new float[9]; inclination = new float[9]; orientation = new float[3]; sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { updateLocation(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; wifiReadings = new LinkedHashMap<String, Integer>(); resetWifiReadings(building); userInitiatedScan = false; }