Java Examples for android.location.LocationListener
The following java examples will help you to understand the usage of android.location.LocationListener. These source code samples are taken from different open source projects.
Example 1
| Project: bearing-master File: LegacyLocationProvider.java View source code |
@Override public String requestSingleLocationUpdate(LocationProviderRequest request, final LocationListener listener) { String provider = getProviderForRequest(request); if (request.useCache) { Location lastKnownUserLocation = locationManager.getLastKnownLocation(provider); // Check if last known location is valid if (lastKnownUserLocation != null && System.currentTimeMillis() - lastKnownUserLocation.getTime() < request.cacheExpiry) { if (lastKnownUserLocation.getAccuracy() < request.accuracy.value) { if (listener != null) { listener.onUpdate(lastKnownUserLocation); return null; } } } } final String requestId = UUID.randomUUID().toString(); runningRequests.put(requestId, new android.location.LocationListener() { @Override public void onLocationChanged(Location location) { if (listener != null) { listener.onUpdate(location); } runningRequests.remove(requestId); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }); locationManager.requestSingleUpdate(provider, runningRequests.get(requestId), Looper.getMainLooper()); return requestId; }
Example 2
| Project: CyclismoProject-master File: DataSource.java View source code |
/**
* Registers a listener for real locations
* @param listener
*/
public void registerRealLocationListener(LocationListener listener) {
// Check if the GPS provider exists
if (myTracksLocationManager.getProvider(LocationManager.GPS_PROVIDER) == null) {
listener.onProviderDisabled(LocationManager.GPS_PROVIDER);
unregisterLocationListener(listener);
return;
}
// Listen for GPS location
myTracksLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
// Update the listener with the current provider state
if (myTracksLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
listener.onProviderEnabled(LocationManager.GPS_PROVIDER);
} else {
listener.onProviderDisabled(LocationManager.GPS_PROVIDER);
}
// Listen for network location
try {
myTracksLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, NETWORK_PROVIDER_MIN_TIME, 0, listener);
} catch (RuntimeException e) {
Log.w(TAG, "Could not register for network location.", e);
}
}Example 3
| Project: JASONETTE-Android-master File: JasonGeoAction.java View source code |
public void get(final JSONObject action, JSONObject data, final JSONObject event, final Context context) {
try {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
try {
JSONObject ret = new JSONObject();
String val = String.format("%f,%f", location.getLatitude(), location.getLongitude());
ret.put("coord", val);
ret.put("value", val);
JasonHelper.next("success", action, ret, event, context);
} catch (Exception e) {
Log.d("Error", e.toString());
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener, Looper.getMainLooper());
} catch (SecurityException e) {
JasonHelper.permission_exception("$geo.get", context);
} catch (Exception e) {
Log.d("Error", e.toString());
}
}Example 4
| Project: kevoree-library-master File: LocationListenerProxy.java View source code |
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 5
| Project: LightSDKAndroid-master File: LocationUtil.java View source code |
public void getLocation(Context context, final Result success) {
manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
String provider = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ? LocationManager.NETWORK_PROVIDER : LocationManager.GPS_PROVIDER;
manager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (success != null) {
success.onFinished(location.getLatitude(), location.getLongitude());
}
manager.removeUpdates(this);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Logger.d(provider);
}
@Override
public void onProviderEnabled(String provider) {
Logger.d(provider);
}
@Override
public void onProviderDisabled(String provider) {
Logger.d(provider);
}
});
}Example 6
| Project: MapLite-master File: LocationListenerProxy.java View source code |
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 7
| Project: MozStumbler-master File: LocationListenerProxy.java View source code |
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 8
| Project: osmdroid-master File: SampleHeadingCompassUp.java View source code |
@Override
public void onResume() {
super.onResume();
//hack for x86
if (!"Android-x86".equalsIgnoreCase(Build.BRAND)) {
//lock the device in current screen orientation
int orientation;
int rotation = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
switch(rotation) {
case Surface.ROTATION_0:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
this.deviceOrientation = 0;
screen_orientation = "ROTATION_0 SCREEN_ORIENTATION_PORTRAIT";
break;
case Surface.ROTATION_90:
this.deviceOrientation = 90;
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
screen_orientation = "ROTATION_90 SCREEN_ORIENTATION_LANDSCAPE";
break;
case Surface.ROTATION_180:
this.deviceOrientation = 180;
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
screen_orientation = "ROTATION_180 SCREEN_ORIENTATION_REVERSE_PORTRAIT";
break;
default:
this.deviceOrientation = 270;
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
screen_orientation = "ROTATION_270 SCREEN_ORIENTATION_REVERSE_LANDSCAPE";
break;
}
getActivity().setRequestedOrientation(orientation);
}
LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
try {
//on API15 AVDs,network provider fails. no idea why
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) this);
} catch (Exception ex) {
}
compass = new InternalCompassOrientationProvider(getActivity());
compass.startOrientationProvider(this);
mMapView.getController().zoomTo(16);
}Example 9
| Project: rex-weather-master File: LocationService.java View source code |
@Override
public void call(final Subscriber<? super Location> subscriber) {
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(final Location location) {
subscriber.onNext(location);
subscriber.onCompleted();
Looper.myLooper().quit();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
final Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationCriteria.setPowerRequirement(Criteria.POWER_LOW);
final String locationProvider = mLocationManager.getBestProvider(locationCriteria, true);
Looper.prepare();
mLocationManager.requestSingleUpdate(locationProvider, locationListener, Looper.myLooper());
Looper.loop();
}Example 10
| Project: glasquare-master File: LocationUtils.java View source code |
public static void getRecentLocation(final LocationListener listener) { Location last = LocationUtils.getLastLocation(); if (last == null || LocationUtils.getAgeInSeconds(last.getTime()) > 60) { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_MEDIUM); final LocationManager locationManager = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE); List<String> providers = locationManager.getProviders(criteria, /* enabledOnly */ true); if (providers.size() == 0) { listener.onLocationFailed(); return; } locationSuccess = false; final android.location.LocationListener locationListener = new android.location.LocationListener() { @Override public void onLocationChanged(Location location) { locationSuccess = true; locationManager.removeUpdates(this); listener.onLocationAcquired(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; for (String provider : providers) { locationManager.requestLocationUpdates(provider, 1000, 5, locationListener); } new Handler().postDelayed(new Runnable() { @Override public void run() { if (!locationSuccess) { locationManager.removeUpdates(locationListener); listener.onLocationFailed(); } } }, 5000); } else { listener.onLocationAcquired(last); } }
Example 11
| Project: android-15-master File: LocationBasedCountryDetector.java View source code |
/**
* Start detecting the country.
* <p>
* Queries the location from all location providers, then starts a thread to query the
* country from GeoCoder.
*/
@Override
public synchronized Country detectCountry() {
if (mLocationListeners != null) {
throw new IllegalStateException();
}
// Request the location from all enabled providers.
List<String> enabledProviders = getEnabledProviders();
int totalProviders = enabledProviders.size();
if (totalProviders > 0) {
mLocationListeners = new ArrayList<LocationListener>(totalProviders);
for (int i = 0; i < totalProviders; i++) {
String provider = enabledProviders.get(i);
if (isAcceptableProvider(provider)) {
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
LocationBasedCountryDetector.this.stop();
queryCountryCode(location);
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
mLocationListeners.add(listener);
registerListener(provider, listener);
}
}
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mTimer = null;
LocationBasedCountryDetector.this.stop();
// Looks like no provider could provide the location, let's try the last
// known location.
queryCountryCode(getLastKnownLocation());
}
}, getQueryLocationTimeout());
} else {
// There is no provider enabled.
queryCountryCode(getLastKnownLocation());
}
return mDetectedCountry;
}Example 12
| Project: android-examples-master File: MainActivity.java View source code |
/**
* Sets location listening.
*/
void setupLocationListening() {
LocationManager locationManager;
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
TextView longitude = (TextView) findViewById(R.id.textView_lon);
TextView latitude = (TextView) findViewById(R.id.textView_lat);
longitude.setText("Longitude:" + location.getLongitude());
latitude.setText("Latitude:" + location.getLatitude());
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
String mprovider;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider, 15000, 1, locationListener);
if (location != null)
locationListener.onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
}Example 13
| Project: android-sdk-sources-for-api-level-23-master File: LocationBasedCountryDetector.java View source code |
/**
* Start detecting the country.
* <p>
* Queries the location from all location providers, then starts a thread to query the
* country from GeoCoder.
*/
@Override
public synchronized Country detectCountry() {
if (mLocationListeners != null) {
throw new IllegalStateException();
}
// Request the location from all enabled providers.
List<String> enabledProviders = getEnabledProviders();
int totalProviders = enabledProviders.size();
if (totalProviders > 0) {
mLocationListeners = new ArrayList<LocationListener>(totalProviders);
for (int i = 0; i < totalProviders; i++) {
String provider = enabledProviders.get(i);
if (isAcceptableProvider(provider)) {
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
LocationBasedCountryDetector.this.stop();
queryCountryCode(location);
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
mLocationListeners.add(listener);
registerListener(provider, listener);
}
}
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mTimer = null;
LocationBasedCountryDetector.this.stop();
// Looks like no provider could provide the location, let's try the last
// known location.
queryCountryCode(getLastKnownLocation());
}
}, getQueryLocationTimeout());
} else {
// There is no provider enabled.
queryCountryCode(getLastKnownLocation());
}
return mDetectedCountry;
}Example 14
| Project: android_frameworks_base-master File: LocationBasedCountryDetector.java View source code |
/**
* Start detecting the country.
* <p>
* Queries the location from all location providers, then starts a thread to query the
* country from GeoCoder.
*/
@Override
public synchronized Country detectCountry() {
if (mLocationListeners != null) {
throw new IllegalStateException();
}
// Request the location from all enabled providers.
List<String> enabledProviders = getEnabledProviders();
int totalProviders = enabledProviders.size();
if (totalProviders > 0) {
mLocationListeners = new ArrayList<LocationListener>(totalProviders);
for (int i = 0; i < totalProviders; i++) {
String provider = enabledProviders.get(i);
if (isAcceptableProvider(provider)) {
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
LocationBasedCountryDetector.this.stop();
queryCountryCode(location);
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
mLocationListeners.add(listener);
registerListener(provider, listener);
}
}
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mTimer = null;
LocationBasedCountryDetector.this.stop();
// Looks like no provider could provide the location, let's try the last
// known location.
queryCountryCode(getLastKnownLocation());
}
}, getQueryLocationTimeout());
} else {
// There is no provider enabled.
queryCountryCode(getLastKnownLocation());
}
return mDetectedCountry;
}Example 15
| Project: apps-master File: MainActivity.java View source code |
/**
* Sets location listening.
*/
void setupLocationListening() {
LocationManager locationManager;
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
TextView longitude = (TextView) findViewById(R.id.textView_lon);
TextView latitude = (TextView) findViewById(R.id.textView_lat);
longitude.setText("Longitude:" + location.getLongitude());
latitude.setText("Latitude:" + location.getLatitude());
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
String mprovider;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider, 15000, 1, locationListener);
if (location != null)
locationListener.onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
}Example 16
| Project: evercam-discover-android-master File: LocationReader.java View source code |
private void launchListener() {
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (currentLocation == null) {
currentLocation = location;
} else {
locationManager.removeUpdates(this);
}
Log.d(TAG, location.getLongitude() + " " + location.getLatitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
// locationManager.requestSingleUpdate(provider, listener, null);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
}Example 17
| Project: folio100_frameworks_base-master File: ExternalSharedPermsFLTest.java View source code |
/** The use of location manager below is simply to simulate an app that
* tries to use it, so we can verify whether permissions are granted and accessible.
* */
public void testRunFineLocation() {
LocationManager locationManager = (LocationManager) getInstrumentation().getContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
});
}Example 18
| Project: frameworks_base_disabled-master File: LocationBasedCountryDetector.java View source code |
/**
* Start detecting the country.
* <p>
* Queries the location from all location providers, then starts a thread to query the
* country from GeoCoder.
*/
@Override
public synchronized Country detectCountry() {
if (mLocationListeners != null) {
throw new IllegalStateException();
}
// Request the location from all enabled providers.
List<String> enabledProviders = getEnabledProviders();
int totalProviders = enabledProviders.size();
if (totalProviders > 0) {
mLocationListeners = new ArrayList<LocationListener>(totalProviders);
for (int i = 0; i < totalProviders; i++) {
String provider = enabledProviders.get(i);
if (isAcceptableProvider(provider)) {
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
LocationBasedCountryDetector.this.stop();
queryCountryCode(location);
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
mLocationListeners.add(listener);
registerListener(provider, listener);
}
}
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mTimer = null;
LocationBasedCountryDetector.this.stop();
// Looks like no provider could provide the location, let's try the last
// known location.
queryCountryCode(getLastKnownLocation());
}
}, getQueryLocationTimeout());
} else {
// There is no provider enabled.
queryCountryCode(getLastKnownLocation());
}
return mDetectedCountry;
}Example 19
| Project: platform-android-master File: BaseLocationObservable.java View source code |
protected void getLocationUpdates(Observer<? super T> observer) {
if (mLocationListener == null) {
throw new IllegalArgumentException("LocationListener cannot be null");
}
try {
if (isNetworkEnabled()) {
mLocationManager.requestLocationUpdates(android.location.LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener, Looper.getMainLooper());
Timber.i("NETWORK_PROVIDER %s", "Enabled");
return;
}
if (isGPSEnabled()) {
mLocationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener, Looper.getMainLooper());
Timber.i("GPS_PROVIDER %s", "Enabled");
}
} catch (Exception e) {
observer.onError(e);
}
}Example 20
| Project: platform_frameworks_base-master File: ExternalSharedPermsFLTest.java View source code |
/** The use of location manager below is simply to simulate an app that
* tries to use it, so we can verify whether permissions are granted and accessible.
* */
public void testRunFineLocation() {
LocationManager locationManager = (LocationManager) getInstrumentation().getContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
});
}Example 21
| Project: property-db-master File: ExternalSharedPermsTest.java View source code |
/** The use of location manager and bluetooth below are simply to simulate an app that
* tries to use them, so we can verify whether permissions are granted and accessible.
* */
public void testRunLocationAndBluetooth() {
LocationManager locationManager = (LocationManager) getInstrumentation().getContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
});
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if ((mBluetoothAdapter != null) && (!mBluetoothAdapter.isEnabled())) {
mBluetoothAdapter.getName();
}
}Example 22
| Project: SVQCOM-master File: LocationServices.java View source code |
public static void getLocation(CheckinActivity activity) {
checkin_activity = activity;
LocationServices.locationSet = false;
final LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
LocationProvider low = locationManager.getProvider(locationManager.getBestProvider(Util.createCoarseCriteria(), true));
// get high accuracy provider
LocationProvider high = locationManager.getProvider(locationManager.getBestProvider(Util.createFineCriteria(), true));
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LocationServices.location = location;
if (LocationServices.location != null) {
LocationServices.locationSet = true;
}
((LocationManager) checkin_activity.getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
dismissActionDialog();
}
public void onProviderDisabled(String provider) {
LocationServices.location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (LocationServices.location != null) {
LocationServices.locationSet = true;
}
((LocationManager) checkin_activity.getSystemService(Context.LOCATION_SERVICE)).removeUpdates(this);
dismissActionDialog();
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
locationManager.requestLocationUpdates(low.getName(), 1000L, 500.0f, locationListener);
locationManager.requestLocationUpdates(high.getName(), 1000L, 500.0f, locationListener);
}Example 23
| Project: Parse-SDK-Android-master File: LocationNotifier.java View source code |
/**
* Asynchronously gets the current location of the device.
*
* This will request location updates from the best provider that match the given criteria
* and return the first location received.
*
* You can customize the criteria to meet your specific needs.
* * For higher accuracy, you can set {@link Criteria#setAccuracy(int)}, however result in longer
* times for a fix.
* * For better battery efficiency and faster location fixes, you can set
* {@link Criteria#setPowerRequirement(int)}, however, this will result in lower accuracy.
*
* @param context
* The context used to request location updates.
* @param timeout
* The number of milliseconds to allow before timing out.
* @param criteria
* The application criteria for selecting a location provider.
*
* @see android.location.LocationManager#getBestProvider(android.location.Criteria, boolean)
* @see android.location.LocationManager#requestLocationUpdates(String, long, float, android.location.LocationListener)
*/
/* package */
static Task<Location> getCurrentLocationAsync(Context context, long timeout, Criteria criteria) {
final TaskCompletionSource<Location> tcs = new TaskCompletionSource<>();
final Capture<ScheduledFuture<?>> timeoutFuture = new Capture<>();
final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
final LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location == null) {
return;
}
timeoutFuture.get().cancel(true);
tcs.trySetResult(location);
manager.removeUpdates(this);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
timeoutFuture.set(ParseExecutors.scheduled().schedule(new Runnable() {
@Override
public void run() {
tcs.trySetError(new ParseException(ParseException.TIMEOUT, "Location fetch timed out."));
manager.removeUpdates(listener);
}
}, timeout, TimeUnit.MILLISECONDS));
String provider = manager.getBestProvider(criteria, true);
if (provider != null) {
manager.requestLocationUpdates(provider, /* minTime */
0, /* minDistance */
0.0f, listener);
}
if (fakeLocation != null) {
listener.onLocationChanged(fakeLocation);
}
return tcs.getTask();
}Example 24
| Project: Blind-Vision-master File: LocationService.java View source code |
private void getLocation() {
lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationlistener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
locMsg = "http://mess.byethost31.com/bv/mloc.php?id=" + bid + "&lat=" + location.getLatitude() + "&lng=" + location.getLongitude();
new UpdateTask().execute();
Toast.makeText(LocationService.this, "Location Updated" + locMsg, Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider) {
String locMsg = "\nGPS provider disabled";
Log.d("Blind Vision", "BootReceiver: Provider disabled");
Toast.makeText(LocationService.this, "GPS Disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
lm.requestLocationUpdates("gps", 1 * 60 * 1000 * 60, 10, locationlistener);
}Example 25
| Project: curso-android-src-master File: MainActivity.java View source code |
private void actualizarPosicion() {
//Obtenemos una referencia al LocationManager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Obtenemos la última posición conocida
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//Mostramos la última posición conocida
muestraPosicion(location);
//Nos registramos para recibir actualizaciones de la posición
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
muestraPosicion(location);
}
public void onProviderDisabled(String provider) {
lblEstado.setText("Provider OFF");
}
public void onProviderEnabled(String provider) {
lblEstado.setText("Provider ON");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("LocAndroid", "Provider Status: " + status);
lblEstado.setText("Provider Status: " + status);
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 15000, 0, locationListener);
}Example 26
| Project: Mapyst-master File: LocationFinder.java View source code |
public void setupLocService() {
mlocManager = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE);
mlocListenerNetwork = new LocationListener() {
@Override
public void onLocationChanged(Location loc) {
currentNetworkLoc = loc;
}
@Override
public void onProviderDisabled(String provider) {
// Toast.makeText(app, "Current Network Location Disabled",
// Toast.LENGTH_LONG);
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListenerNetwork);
mlocListenerGps = new LocationListener() {
@Override
public void onLocationChanged(Location loc) {
currentGpsLoc = loc;
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(app, "Current GPS Location Disabled", Toast.LENGTH_LONG).show();
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListenerGps);
}Example 27
| Project: QuarkUpto29May-master File: CMCCellIdInfoUpdateService.java View source code |
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "CMCCellInfoUpdateSewrvice Service Started ", Toast.LENGTH_LONG).show();
lmgr = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
locLis = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
currentLocation = location;
if (currentLocation != null) {
float[] result = new float[5];
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), 28.695833, 77.1525, result);
if (result[0] <= 500) {
Toast.makeText(context, "The Distance is " + result[0], Toast.LENGTH_SHORT).show();
sp = getSharedPreferences("cellId_info", MODE_PRIVATE);
SharedPreferences.Editor sped = sp.edit();
sped.putInt("cellId", cellId);
sped.commit();
Toast.makeText(context, "Cell Id Saved " + cellId, Toast.LENGTH_SHORT).show();
stopSelf();
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch(status) {
case LocationProvider.AVAILABLE:
Toast.makeText(context, "Now " + provider + " Location Info is available ", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.OUT_OF_SERVICE:
Toast.makeText(context, "Now " + provider + " is Out of Service ", Toast.LENGTH_SHORT).show();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Toast.makeText(context, "Now " + provider + " is temporary unavailable ", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(context, "Now " + provider + " is Enabled ", Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(context, "Now " + provider + " is Disabled ", Toast.LENGTH_SHORT).show();
}
};
lmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 60 * 1000, 1000, locLis);
telmgr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
cellLocationListener = new PhoneStateListener() {
@Override
public void onCellLocationChanged(CellLocation location) {
GsmCellLocation gsmCellLocation = (GsmCellLocation) location;
Toast.makeText(context, " Cell Id " + String.valueOf(gsmCellLocation.getCid()) + " Cell LAC " + String.valueOf(gsmCellLocation.getLac()) + " Cell PAC " + String.valueOf(gsmCellLocation.getPsc()), Toast.LENGTH_LONG).show();
cellId = gsmCellLocation.getCid();
}
};
telmgr.listen(cellLocationListener, PhoneStateListener.LISTEN_CELL_LOCATION);
return START_STICKY;
}Example 28
| Project: samples-master File: HelloAndroidGpsActivity.java View source code |
/** Gets the current location and update the mobileLocation variable*/
private void getCurrentLocation() {
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mobileLocation = location;
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}Example 29
| Project: sun-status-app-master File: LocationUtils.java View source code |
/**
make sure to call this in the main thread, not a background thread
make sure to call locMgr.removeUpdates(...) when you are done
*/
public static void init(Context ctx, LocationManager locMgr) {
//LocationManager locMgr = LocationUtils.getLocationManager(ctx.getMyContext());
// get low accuracy provider
LocationProvider low = locMgr.getProvider(locMgr.getBestProvider(createCoarseCriteria(), true));
// get high accuracy provider
LocationProvider high = locMgr.getProvider(locMgr.getBestProvider(createFineCriteria(), true));
// using low accuracy provider... to listen for updates
locMgr.requestLocationUpdates(low.getName(), 0, 0f, new LocationListener() {
public void onLocationChanged(Location location) {
// do something here to save this new location
}
public void onStatusChanged(String s, int i, Bundle bundle) {
}
public void onProviderEnabled(String s) {
// try switching to a different provider
}
public void onProviderDisabled(String s) {
// try switching to a different provider
}
});
// using high accuracy provider... to listen for updates
locMgr.requestLocationUpdates(high.getName(), 0, 0f, new LocationListener() {
public void onLocationChanged(Location location) {
// do something here to save this new location
}
public void onStatusChanged(String s, int i, Bundle bundle) {
}
public void onProviderEnabled(String s) {
// try switching to a different provider
}
public void onProviderDisabled(String s) {
// try switching to a different provider
}
});
}Example 30
| Project: traccar-client-android-master File: MixedPositionProvider.java View source code |
private void startBackupProvider() {
Log.i(TAG, "backup provider start");
if (backupListener == null) {
backupListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i(TAG, "backup provider location");
updateLocation(location);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, requestInterval, 0, backupListener);
}
}Example 31
| Project: WiCamera3D-master File: GetGPSInfo.java View source code |
public Location getGps() {
// 创建LocationManager对象
m_locManager = (LocationManager) m_context.getSystemService(Context.LOCATION_SERVICE);
// 从GPS获�最近的gps信�
m_locations = m_locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// 使用locationæ ¹æ?®EditText的显示
// �3秒获�gps信�
m_locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 8, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// 当GPS定�信��生改�时,更新�置
m_locations = location;
}
@Override
public void onProviderDisabled(String provider) {
m_locations = null;
}
@Override
public void onProviderEnabled(String provider) {
// 当GPS LocationProvider�用时更新�置
m_locations = m_locManager.getLastKnownLocation(provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
});
if (m_locations != null) {
System.out.println("df" + m_locations.getLatitude() + "s" + m_locations.getLongitude());
Toast.makeText(m_context, m_locations.getLatitude() + "s" + m_locations.getLongitude(), 1000);
}
return m_locations;
}Example 32
| Project: ajapaik-android-master File: MainFragment.java View source code |
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View v = super.onCreateView(inflater, viewGroup, savedInstanceState);
map = getMap();
map.setMyLocationEnabled(true);
map.getUiSettings().setCompassEnabled(true);
if (savedInstanceState == null) {
CameraUpdate[] updates = new CameraUpdate[] { CameraUpdateFactory.newLatLng(new LatLng(58.378195d, 26.714388d)), CameraUpdateFactory.zoomTo(15.0f) };
for (CameraUpdate u : updates) {
map.moveCamera(u);
}
LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
// gps provider doesn't mean anything
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(cameraPosition.target.latitude);
loc.setLongitude(cameraPosition.target.longitude);
loadPhotoList(loc);
}
});
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_MEDIUM);
lm.requestSingleUpdate(crit, new LocationListener() {
@Override
public void onLocationChanged(Location loc) {
map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(loc.getLatitude(), loc.getLongitude())));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
}, null);
}
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
DetailsActivity.start(getActivity(), Integer.valueOf(marker.getSnippet()), marker.getTitle());
return true;
}
});
return v;
}Example 33
| Project: android-sensorium-master File: GPSLocationSensor.java View source code |
@Override
protected void _enable() {
Log.d("GPS", "ENABLING GPS");
locationListener = new LocationListener() {
public void onLocationChanged(Location loc) {
longitude.setValue(loc.getLongitude());
latitude.setValue(loc.getLatitude());
altitude.setValue(loc.getAltitude());
accuracy.setValue(loc.getAccuracy());
bearing.setValue(loc.getBearing());
speed.setValue(loc.getSpeed());
timeMillis = loc.getTime();
Geocoder myLocation = new Geocoder(getContext().getApplicationContext(), Locale.getDefault());
List<Address> list = null;
try {
list = myLocation.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address location = list.get(0);
String addressText = String.format("%s, %s, %s", location.getMaxAddressLineIndex() > 0 ? location.getAddressLine(0) : "", // location.getAdminArea(),
location.getLocality(), location.getCountryName());
address.setValue(addressText);
} else
address.setValue("n/a");
} catch (IOException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
Log.d(SensorRegistry.TAG, sw.toString());
}
notifyListeners();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
Log.d("LocationSensor", provider + " enabled, listening for updates.");
}
public void onProviderDisabled(String provider) {
Log.d("LocationSensor", provider + " disabled, no more updates.");
}
};
gpsStatusListener = new Listener() {
@Override
public void onGpsStatusChanged(int event) {
if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) {
GpsStatus gpsstatus = locationManager.getGpsStatus(null);
Iterable<GpsSatellite> gpsit = gpsstatus.getSatellites();
int numsat = 0;
for (GpsSatellite sat : gpsit) {
numsat++;
}
satellites.setValue(numsat);
notifyListeners();
}
}
};
locationManager = ((LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE));
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_UPDATE_TIME_INTERVAL, GPS_UPDATE_MINIMAL_DISTANCE, locationListener);
locationManager.addGpsStatusListener(gpsStatusListener);
}Example 34
| Project: AndroidExercise-master File: MainActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//�始化百度地图
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.map_view);
baiduMap = mapView.getMap();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
List<String> providerList = locationManager.getProviders(true);
if (providerList.contains(LocationManager.GPS_PROVIDER)) {
provider = LocationManager.GPS_PROVIDER;
} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {
provider = LocationManager.NETWORK_PROVIDER;
} else {
Toast.makeText(this, "No location provider to use", Toast.LENGTH_SHORT).show();
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
navigateTo(location);
}
locationManager.requestLocationUpdates(provider, 3000, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
navigateTo(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
});
}Example 35
| Project: AndroidTutorialForBeginners-master File: MapsActivity.java View source code |
void LocationListner() {
LocationListener locationListener = new MyLocationListener(this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3, 3, locationListener);
myThread m_thread = new myThread();
m_thread.start();
}Example 36
| Project: Appsii-master File: WeatherLoadingServiceTest.java View source code |
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Looper looper = (Looper) invocation.getArguments()[2];
final LocationListener l = (LocationListener) invocation.getArguments()[1];
if (looper != null) {
Handler h = new Handler(looper);
h.postDelayed(new Runnable() {
@Override
public void run() {
l.onLocationChanged(loc);
}
}, mWaitTime);
} else {
l.onLocationChanged(loc);
}
return null;
}Example 37
| Project: ARKOST-master File: Rute.java View source code |
public void getGPS() {
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ls = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
tampilPeta(location);
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1000, ls);
}Example 38
| Project: beyondar-master File: BeyondarLocationManager.java View source code |
public void registerLocationListener(LocationListener locationListener, GpsStatus.Listener gpsListener) {
if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
mLocationManager.addGpsStatusListener(gpsListener);
}
if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}Example 39
| Project: CityBikes-master File: Locator.java View source code |
public void startUpdates(boolean instantLastLocation) {
status = RUNNING;
//Log.i("CityBikes","Starting all location updates");
listeners = new LinkedList<LocationListener>();
LocationListener ll;
for (Iterator<String> i = locationManager.getProviders(true).iterator(); i.hasNext(); ) {
ll = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (!locked)
update(location);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
listeners.add(ll);
locationManager.requestLocationUpdates(i.next(), 60000, 25, ll);
}
if (instantLastLocation) {
update(getLastKnownLocation());
}
}Example 40
| Project: congress-android-master File: LocationUtils.java View source code |
public static LocationTimer requestLocationUpdate(Context context, Handler handler, String provider) {
Log.d(Utils.TAG, "LocationUtils - requestLocationUpdate(): from provider " + provider);
if (!(context instanceof LocationListener))
throw new IllegalArgumentException("context must implement LocationListener to receive updates!");
LocationListenerTimeout listener = (LocationListenerTimeout) context;
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationTimer timer = new LocationTimer(listener, manager, provider, handler);
timer.start();
return timer;
}Example 41
| Project: cos598b-master File: PredictionRequestReceiver.java View source code |
private void doLocationScan() {
LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setBearingRequired(true);
criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
criteria.setSpeedRequired(true);
criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location arg0) {
onLocation(arg0);
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
try {
lm.requestSingleUpdate(criteria, locationListener, null);
} catch (Exception e) {
callback("location not available");
}
}Example 42
| Project: FileSpace-Android-master File: GpsUtils.java View source code |
public static Location getGpsLocation(Context context, final ILocationListener locationListener) {
LocationManager myLocationManager;
String PROVIDER = LocationManager.GPS_PROVIDER;
myLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
myLocationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
locationListener.execute(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}, Looper.myLooper());
//get last known location, if available
return myLocationManager.getLastKnownLocation(PROVIDER);
}Example 43
| Project: GeoNFC-master File: DeviceInformation.java View source code |
public void startLocating(final Activity activity, final int delay) {
String locManager = "";
locManager = LocationManager.GPS_PROVIDER;
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
if (locationListener == null)
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
loc = location;
timer.cancel();
timer.purge();
handleGpsLoc(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
if (locationListener != null)
locationManager.requestLocationUpdates(locManager, delay, 0, locationListener);
}Example 44
| Project: Go2-Rennes-master File: LocationUtils.java View source code |
private void addListener(LocationListener listener) {
List<String> providers = locationManager.getAllProviders();
if (providers.contains(LocationManager.GPS_PROVIDER) && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000L, 0L, listener);
}
if (providers.contains(LocationManager.NETWORK_PROVIDER) && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 0L, listener);
}
}Example 45
| Project: hellomap3d-android-master File: MyLocationActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
// MapSampleBaseActivity creates and configures mapView
super.onCreate(savedInstanceState);
final Projection proj = super.baseProjection;
// Initialize an local vector data source where to put my location circle
LocalVectorDataSource vectorDataSource = new LocalVectorDataSource(proj);
// Initialize a vector layer with the previous data source
VectorLayer vectorLayer = new VectorLayer(vectorDataSource);
// Add the previous vector layer to the map
mapView.getLayers().add(vectorLayer);
// style for GPS My Location circle
PolygonStyleBuilder polygonStyleBuilder = new PolygonStyleBuilder();
polygonStyleBuilder.setColor(new Color(0xAAFF0000));
PolygonStyle gpsStyle = polygonStyleBuilder.buildStyle();
MapPosVector gpsCirclePoses = new MapPosVector();
final Polygon locationCircle = new Polygon(gpsCirclePoses, gpsStyle);
// initially empty and invisible
locationCircle.setVisible(false);
vectorDataSource.add(locationCircle);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.debug("GPS onLocationChanged " + location);
if (locationCircle != null) {
locationCircle.setPoses(CircleUtil.createLocationCircle(location, proj));
locationCircle.setVisible(true);
mapView.setFocusPos(proj.fromWgs84(new MapPos(location.getLongitude(), location.getLatitude())), 0.5f);
// zoom 2, duration 0 seconds (no animation)
mapView.setZoom(14, 1.0f);
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// user has maybe disabled location services / GPS
if (locationManager.getProviders(true).size() == 0) {
Toast.makeText(this, "Cannot get location, no location providers enabled. Check device settings", Toast.LENGTH_LONG).show();
}
// use all enabled device providers with same parameters
for (String provider : locationManager.getProviders(true)) {
Log.debug("adding location provider " + provider);
locationManager.requestLocationUpdates(provider, 1000, 50, locationListener);
}
}Example 46
| Project: LOST-master File: FusedLocationProviderServiceDelegate.java View source code |
@RequiresPermission(anyOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION })
public void reportProviderEnabled(String provider) {
notifyLocationAvailabilityChanged();
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
manager.requestSingleUpdate(provider, new android.location.LocationListener() {
@Override
public void onLocationChanged(Location location) {
notifyLocationAvailabilityChanged();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}, Looper.myLooper());
}Example 47
| Project: nptornews-master File: NewsApplication.java View source code |
/**
* On start up, launch a location listener for each service. We need to do
* this in order to ensure that getLastKnownLocation, used to find local
* stations, will always find a value.
*/
private void launchLocationListeners() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(false);
for (String provider : providers) {
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
handler.sendEmptyMessage(MSG_CANCEL_LOCATION_LISTENERS);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
lm.requestLocationUpdates(provider, 60000, 0, listener);
locationListeners.add(listener);
}
}Example 48
| Project: RxWeather-master File: PrepareCase.java View source code |
@Override
public void call(final Subscriber<? super Location> subscriber) {
final LocationListener locationListener = new LocationListenerAdapter() {
public void onLocationChanged(final Location location) {
if (!subscriber.isUnsubscribed()) {
subscriber.onNext(location);
subscriber.onCompleted();
}
locationManager.removeUpdates(this);
handlerThread.getLooper().quit();
}
};
subscriber.add(new MainThreadSubscription() {
@Override
protected void onUnsubscribe() {
locationManager.removeUpdates(locationListener);
handlerThread.getLooper().quit();
}
});
final Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationCriteria.setPowerRequirement(Criteria.POWER_LOW);
final String locationProvider = locationManager.getBestProvider(locationCriteria, true);
locationManager.requestSingleUpdate(locationProvider, locationListener, handlerThread.getLooper());
}Example 49
| Project: socialize-sdk-android-master File: LocationUtilsTest.java View source code |
public void testGetLocation() {
final Location mockLocation = new Location((String) null);
mockLocation.setLatitude(69);
mockLocation.setLongitude(96);
// Stub in location provider and manager
SocializeLocationManager mockLocationManager = new SocializeLocationManager(null) {
@Override
public void init(Context context) {
}
@Override
public String getBestProvider(Criteria criteria, boolean enabledOnly) {
return "foobar";
}
@Override
public Location getLastKnownLocation(String provider) {
return mockLocation;
}
@Override
public boolean isProviderEnabled(String provider) {
return true;
}
@Override
public void requestLocationUpdates(Activity activity, String provider, long minTime, float minDistance, LocationListener listener) {
}
@Override
public void removeUpdates(LocationListener listener) {
}
};
SocializeLocationProvider mockLocationProvider = new DefaultLocationProvider() {
@Override
public Location getLastKnownLocation() {
return mockLocation;
}
@Override
public Location getLocation(Context context) {
return mockLocation;
}
};
SocializeIOC.registerStub("locationManager", mockLocationManager);
SocializeIOC.registerStub("locationProvider", mockLocationProvider);
Location location = LocationUtils.getLastKnownLocation(getContext());
SocializeIOC.unregisterStub("locationManager");
SocializeIOC.unregisterStub("locationProvider");
assertNotNull(location);
assertEquals(mockLocation.getLongitude(), location.getLongitude());
assertEquals(mockLocation.getLatitude(), location.getLatitude());
}Example 50
| Project: Tweetin-master File: PostTask.java View source code |
private GeoLocation getGeoLocation() {
LocationManager locationManager = (LocationManager) postActivity.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
});
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
return new GeoLocation(location.getLatitude(), location.getLongitude());
}
return null;
}Example 51
| Project: Zappit-master File: LocationService.java View source code |
@Override
protected void onHandleIntent(Intent intent) {
LocationListener gpsListener = new LocationListener() {
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
Log.d(TAG, "STATUS CHANGE");
}
@Override
public void onProviderEnabled(String arg0) {
Log.d(TAG, "ENABLED");
}
@Override
public void onProviderDisabled(String arg0) {
Log.d(TAG, "DISABLED");
}
@Override
public void onLocationChanged(Location location) {
updateLocation(location);
}
};
LocationListener networkListener = new LocationListener() {
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
Log.d(TAG, "STATUS CHANGE");
}
@Override
public void onProviderEnabled(String arg0) {
Log.d(TAG, "ENABLED");
}
@Override
public void onProviderDisabled(String arg0) {
Log.d(TAG, "DISABLED");
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "NETWORK LOCATION CHANGED");
updateLocation(location);
}
};
Log.d(TAG, "STARTING LISTENING");
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);
for (String string : locationManager.getProviders(true)) {
Log.d(TAG, "Provider:" + string);
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0.0f, networkListener);
clearLocation();
int timeCount = 0;
int locationCount = 0;
while (true) {
synchronized (this) {
timeCount++;
Log.d(TAG, "STILL WAITING FOR LOCATION");
try {
wait(2000);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.d(TAG, "GPS found");
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d(TAG, "Network found");
}
}
//after 8 minutes give up as this will kill the battery
if (location != null) {
Log.d(TAG, "Found location no:" + locationCount);
locationCount++;
}
if (locationCount > 2 || timeCount > 10) {
updateLocation(location);
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
stopSelf();
break;
}
} catch (NullPointerException e) {
} catch (InterruptedException e) {
}
}
}
}Example 52
| Project: android-context-master File: GPSService.java View source code |
public void startService() {
getPrefs();
listener = new LocationListener() {
public void onLocationChanged(Location location) {
isreliable = true;
currentLocation.set(location);
if (DEBUG) {
Log.i(TAG, "New location found: [" + location.getLongitude() + "," + location.getLatitude() + "] | Speed: [" + location.getSpeed() + "]");
}
}
public void onProviderDisabled(String provider) {
//manager.removeUpdates(this);
if (DEBUG) {
Log.i(TAG, locationType + ": is no longer reliable");
}
isreliable = false;
if (DEBUG_TTS) {
ContextExpandableListActivity.tts.speak("GPS reliability is " + String.valueOf(isreliable), TextToSpeech.QUEUE_FLUSH, null);
}
}
public void onProviderEnabled(String provider) {
Log.i(TAG, locationType + ": is reliable");
//isreliable = true;
if (DEBUG_TTS) {
ContextExpandableListActivity.tts.speak("GPS reliability is " + String.valueOf(isreliable), TextToSpeech.QUEUE_FLUSH, null);
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
switch(status) {
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
isreliable = false;
if (DEBUG_TTS) {
ContextExpandableListActivity.tts.speak("GPS reliability is " + String.valueOf(isreliable), TextToSpeech.QUEUE_FLUSH, null);
}
if (DEBUG) {
Log.i(TAG, "GPS Temporarily unavailable");
}
break;
case LocationProvider.AVAILABLE:
isreliable = true;
if (DEBUG_TTS) {
ContextExpandableListActivity.tts.speak("GPS reliability is " + String.valueOf(isreliable), TextToSpeech.QUEUE_FLUSH, null);
}
if (DEBUG) {
Log.i(TAG, "GPS Available");
}
break;
default:
if (DEBUG_TTS) {
ContextExpandableListActivity.tts.speak("Other GPS event detected", TextToSpeech.QUEUE_FLUSH, null);
}
if (DEBUG) {
Log.i(TAG, "GPS State unkown");
}
}
// TODO Check the status here to update isreliable
}
};
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
currentLocation = manager.getLastKnownLocation(locationType);
manager.requestLocationUpdates(locationType, 0, 0, listener);
IntentFilter restartFilter = new IntentFilter();
restartFilter.addAction(ContextConstants.CONTEXT_RESTART_INTENT);
registerReceiver(restartIntentReceiver, restartFilter);
running = true;
}Example 53
| Project: AndroidProjectStroe-master File: GpsThread.java View source code |
private void initLintener() {
locationListener = new LocationListener() {
// 底层获得的�置会通过这个接�上报给应用
@Override
public void onLocationChanged(Location location) {
System.out.println("onLocationChanged");
// æ›´æ–°ä½?ç½®
updateWithNewLocation(location);
}
// Provider被disable时触å?‘æ¤å‡½æ•°ï¼Œæ¯”如GPS被关é—
@Override
public void onProviderDisabled(String provider) {
System.out.println("onProviderDisabled");
stopGspListener();
}
// Provider被enable时触å?‘æ¤å‡½æ•°ï¼Œæ¯”如GPS被打开
@Override
public void onProviderEnabled(String provider) {
System.out.println("onProviderEnabled");
updateWithNewLocation(location);
}
/*
* ä½?ç½®æœ?务状æ€?çš„å?˜åŒ–通过这个接å?£ä¸ŠæŠ¥ Provider的转æ€?在å?¯ç”¨ã€?暂时ä¸?å?¯ç”¨å’Œæ— æœ?务三个状æ€?直接切æ?¢æ—¶è§¦å?‘æ¤å‡½æ•°
*/
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
System.out.println("onStatusChanged");
}
};
}Example 54
| Project: apigee-android-sdk-master File: StartActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.geosearch_view);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/* Define a listener that responds to location updates. In this case, we will only use the
the onLocatoinChanged callback */
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
userLocation = location;
setContentView(R.layout.start_view);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
switch(status) {
case LocationProvider.AVAILABLE:
// ...
break;
case LocationProvider.OUT_OF_SERVICE:
// ...
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
// ...
break;
}
// Do something if the status of the location provider changes
}
public void onProviderEnabled(String provider) {
// Do something when the location provider is first enabled
}
public void onProviderDisabled(String provider) {
// Do something when the location provider is disabled
}
};
// Request location updates. In this case, we will use GPS with LocationManager.GPS_PROVIDER.
// You could use the geoIP with LocationManager.NETWORK_PROVIDER
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}Example 55
| Project: application-cafe-jeunesse-android-master File: GoogleMapFragment.java View source code |
private void setUpMap() {
// Trigger les clics sur les descriptions des markers
mMap.setOnInfoWindowClickListener(this);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker arg0) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
View v = getActivity().getLayoutInflater().inflate(R.layout.fragment_googlemap_info_marker, null);
TextView info_title = (TextView) v.findViewById(R.id.marker_title);
info_title.setText(marker.getTitle());
//info.setText(marker.getSnippet());
return v;
}
});
mMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = mLocationManager.getBestProvider(criteria, true);
// Getting Current Location
mLocation = mLocationManager.getLastKnownLocation(provider);
mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
mLocation = location;
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
loadMarkers();
mLocationManager.requestLocationUpdates(provider, MAPS_LOCATION_UPDATE, 0, mLocationListener);
}Example 56
| Project: ASA-master File: LocationHook.java View source code |
public Void invoked(final LocationManager hooked, final Object... args) throws Throwable {
String classname = LocationSettings.class.getName();
Object[] properties = getProperties(classname);
if (properties[0].equals("Real"))
return invoke(hooked, args);
Location location = getLocationIn(Double.parseDouble((String) properties[0]), Double.parseDouble((String) properties[1]), (String) args[0]);
try {
LocationListener listener = (LocationListener) args[5];
fakeListener.setListener(listener);
fakeListener.setLocation(location);
args[5] = fakeListener;
} catch (Exception e) {
try {
Log.d(Utilities.DEBUG, "_requestUpdates was called with PendingIntent, ASA");
PendingIntent intent = (PendingIntent) args[5];
} catch (Exception e2) {
Log.d(Utilities.ERROR, "The argument should be LocationListener or PendingIntent");
}
}
return invoke(hooked, args);
}Example 57
| Project: Capture-the-Flag-Android-Client-master File: CurrentUser.java View source code |
/**
* Periodically updates the users location.
* @param lm
* @param frequency
*/
public static void userLocation(LocationManager lm, int frequency) {
// Setup our location manager
locationManager = lm;
// Remove all updates for the current listener (if one exists)
CurrentUser.stopLocation(lm);
// Setup our location listener
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i(TAG, "Update Location.");
CurrentUser.setLocation(location.getLatitude(), location.getLongitude());
CurrentUser.setAccuracy(location.getAccuracy());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Minimum distance to move a gps update
int distThreshold = 0;
switch(frequency) {
case JoinCTF.GPS_UPDATE_FREQUENCY_GAME:
distThreshold = JoinCTF.GPS_UPDATE_DISTANCE_GAME;
break;
case JoinCTF.GPS_UPDATE_FREQUENCY_INTRO:
distThreshold = JoinCTF.GPS_UPDATE_DISTANCE_INTRO;
break;
case JoinCTF.GPS_UPDATE_FREQUENCY_BACKGROUND:
distThreshold = JoinCTF.GPS_UPDATE_DISTANCE_BACKGROUND;
break;
}
// Start requesting updates per given time
Log.i(TAG, "New GPS Parsing: FREQ=" + frequency + ", DIST=" + distThreshold);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, frequency, distThreshold, locationListener);
}Example 58
| Project: cg_starter-master File: GpsActivity.java View source code |
@Override
protected void onResume() {
super.onResume();
netListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
locationChanged(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
try {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, netListener);
} else {
netListener = null;
}
} catch (Exception ex) {
netListener = null;
}
if ((netListener == null) || need_fine) {
gpsListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
locationChanged(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, gpsListener);
} catch (Exception ex) {
gpsListener = null;
}
}
locationChanged(getLastBestLocation());
}Example 59
| Project: coursera-android-master File: LocationGetLocationActivity.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAccuracyView = (TextView) findViewById(R.id.accuracy_view);
mTimeView = (TextView) findViewById(R.id.time_view);
mLatView = (TextView) findViewById(R.id.lat_view);
mLngView = (TextView) findViewById(R.id.lng_view);
// Acquire reference to the LocationManager
if (null == (mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)))
finish();
// Get best last location measurement
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
// Display last reading information
if (null != mBestReading) {
updateDisplay(mBestReading);
} else {
mAccuracyView.setText("No Initial Reading Available");
}
mLocationListener = new LocationListener() {
// Called back when location changes
public void onLocationChanged(Location location) {
ensureColor();
if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {
// Update best estimate
mBestReading = location;
// Update display
updateDisplay(location);
if (mBestReading.getAccuracy() < MIN_ACCURACY)
mLocationManager.removeUpdates(mLocationListener);
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// NA
}
public void onProviderEnabled(String provider) {
// NA
}
public void onProviderDisabled(String provider) {
// NA
}
};
}Example 60
| Project: geopaparazzi-master File: TestMock.java View source code |
/**
* Starts to trigger mock locations.
*
* @param locationManager the location manager.
* @param locationListener the gps service.
*/
public static void startMocking(final LocationManager locationManager, LocationListener locationListener) {
if (isOn) {
return;
}
if (fakeGpsLog == null) {
fakeGpsLog = new DefaultFakeGpsLog();
}
// Get some mock location data in the game
// LocationProvider provider = locationManager.getProvider(MOCK_PROVIDER_NAME);
// if (provider == null) {
//
locationManager.addTestProvider(//
MOCK_PROVIDER_NAME, //
false, //
false, //
false, //
false, //
true, //
true, //
false, //
Criteria.POWER_LOW, //
Criteria.ACCURACY_FINE);
locationManager.setTestProviderEnabled(MOCK_PROVIDER_NAME, true);
locationManager.requestLocationUpdates(TestMock.MOCK_PROVIDER_NAME, 2000, 0f, locationListener);
try {
locationJellyBeanFixMethod = Location.class.getMethod("makeComplete");
} catch (Exception e1) {
}
Runnable r = new Runnable() {
public void run() {
isOn = true;
long previousT = -1;
long t = 0;
while (isOn) {
String nextLine = null;
if (fakeGpsLog.hasNext()) {
nextLine = fakeGpsLog.next();
String[] lineSplit = nextLine.split(",");
t = Long.parseLong(lineSplit[0]);
double lon = Double.parseDouble(lineSplit[1]);
double lat = Double.parseDouble(lineSplit[2]);
double alt = Double.parseDouble(lineSplit[3]);
float v = Float.parseFloat(lineSplit[4]);
float accuracy = Float.parseFloat(lineSplit[5]);
Location location = new Location(MOCK_PROVIDER_NAME);
location.setLatitude(lat);
location.setLongitude(lon);
location.setTime(t);
location.setAltitude(alt);
location.setAccuracy(accuracy);
location.setSpeed(v);
if (locationJellyBeanFixMethod != null) {
try {
locationJellyBeanFixMethod.invoke(location);
} catch (Exception e) {
GPLog.error(this, null, e);
}
}
location.setSpeed(v);
//
locationManager.setTestProviderStatus(//
MOCK_PROVIDER_NAME, //
LocationProvider.AVAILABLE, //
null, //
SystemClock.elapsedRealtime());
locationManager.setTestProviderLocation(MOCK_PROVIDER_NAME, location);
} else {
fakeGpsLog.reset();
}
try {
if (previousT < 0) {
Thread.sleep(2000);
} else {
long millis = t - previousT;
// Log.i("MOCK_PROVIDER_NAME", nextLine + "///" + millis);
if (millis < 0) {
millis = 2000;
}
Thread.sleep(millis);
}
previousT = t;
} catch (InterruptedException e) {
GPLog.error(this, e.getLocalizedMessage(), e);
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
}Example 61
| Project: Klyph-master File: PlacePickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
try {
Location location = null;
// Instantiate the default criteria for a location provider
Criteria criteria = new Criteria();
// Get a location manager from the system services
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Get the location provider that best matches the criteria
String bestProvider = locationManager.getBestProvider(criteria, false);
if (bestProvider != null) {
// Get the user's last known location
location = locationManager.getLastKnownLocation(bestProvider);
if (locationListener == null) {
// Set up a location listener if one is not already set
// up
// and the selected provider is enabled
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// On location updates, compare the current
// location to the desired location set in the
// place picker
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
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(LocationManager.NETWORK_PROVIDER, 1, LOCATION_CHANGE_THRESHOLD, locationListener);
}
}
if (location == null) {
// Todo : set default location the last saved location
location = SAN_FRANCISCO_LOCATION;
}
if (location != null) {
// Configure the place picker: search center, radius,
// query, and maximum results.
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
// Start the API call
placePickerFragment.loadData(true);
}
/*
* else { // If no location found, show an error
* onError(getResources().getString(R.string.no_location_error),
* true); }
*/
} catch (Exception ex) {
onError(ex);
}
}Example 62
| Project: kuliah_mobile-master File: LocationGetLocationActivity.java View source code |
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAccuracyView = (TextView) findViewById(R.id.accuracy_view);
mTimeView = (TextView) findViewById(R.id.time_view);
mLatView = (TextView) findViewById(R.id.lat_view);
mLngView = (TextView) findViewById(R.id.lng_view);
// Acquire reference to the LocationManager
if (null == (mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE)))
finish();
// Get best last location measurement
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
// Display last reading information
if (null != mBestReading) {
updateDisplay(mBestReading);
} else {
mAccuracyView.setText("No Initial Reading Available");
}
mLocationListener = new LocationListener() {
// Called back when location changes
public void onLocationChanged(Location location) {
ensureColor();
if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {
// Update best estimate
mBestReading = location;
// Update display
updateDisplay(location);
if (mBestReading.getAccuracy() < MIN_ACCURACY)
mLocationManager.removeUpdates(mLocationListener);
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// NA
}
public void onProviderEnabled(String provider) {
// NA
}
public void onProviderDisabled(String provider) {
// NA
}
};
}Example 63
| Project: Locast-Android-master File: IncrementalLocator.java View source code |
/**
* Registers a locationListener, which will immediately get the last known
* location (if there is one). When location updates are no longer needed or
* when the activity is paused, please
* {@link #removeLocationUpdates(LocationListener)}.
*
* This can safely be called multiple times for the same listener.
*
* @param locationListener
*/
public void requestLocationUpdates(LocationListener locationListener) {
// stop any existing location listeners or back out if we're already registered
if (mLocationListener != null) {
if (mLocationListener != locationListener) {
removeLocationUpdates(mLocationListener);
} else {
// we're already registered.
return;
}
}
mLocationListener = locationListener;
final String roughProvider = lm.getBestProvider(initialCriteria, true);
if (roughProvider == null) {
Toast.makeText(mContext, mContext.getString(R.string.error_no_providers), Toast.LENGTH_LONG).show();
return;
}
final Location loc = lm.getLastKnownLocation(roughProvider);
if (loc != null) {
mLocationListener.onLocationChanged(loc);
}
requestLocationUpdates(roughProvider);
if (currentProvider != null) {
requestLocationUpdates(currentProvider);
} else {
Toast.makeText(mContext, R.string.error_no_providers, Toast.LENGTH_LONG).show();
}
}Example 64
| Project: mfh-app-framework-master File: MfLocationManagerProxy.java View source code |
public void requestLocationData(long interval, float distance, LocationListener listener) {
//获å?–缓å˜ä¸çš„ä½?置信æ?¯
Location location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
// Log.d("Nat: LastKnownLocation", String.format("Latitude:%f, longigude:%f", (location.getLatitude() * 1E6), (location.getLongitude() * 1E6)));
MLog.d(String.format("LastKnownLocation: Latitude:%f, longigude:%f", location.getLatitude(), location.getLongitude()));
}
// java.lang.IllegalArgumentException: provider doesn't exist: gps
if (locMgr.getAllProviders().indexOf(LocationManager.GPS_PROVIDER) >= 0) {
//注册�置更新监�(最�时间间隔为5秒,最��离间隔为5米)
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval, distance, listener);
MLog.d("requestLocationUpdates: GPS_PROVIDER");
}
//网络定ä½?ï¼Œåœ¨æ²¡æœ‰ç½‘ç»œçš„æ—¶å€™æ— æ³•èŽ·å¾—ä½?置信æ?¯ã€‚(推è??å’ŒGPS定ä½?å?Œæ—¶ä½¿ç”¨)
if (locMgr.getAllProviders().indexOf(LocationManager.NETWORK_PROVIDER) >= 0) {
//注册�置更新监�(最�时间间隔为5秒,最��离间隔为5米)
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval, distance, listener);
MLog.d("requestLocationUpdates: NETWORK_PROVIDER");
}
}Example 65
| Project: MySnippetRepo-master File: GpsTask.java View source code |
private void gpsInit() {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
handler = new GpsHandler();
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
} else {
//GPSûÓдò¿ª
TIME_OUT = true;
}
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(Location l) {
DATA_CONNTECTED = true;
Message msg = handler.obtainMessage();
msg.what = 0;
msg.obj = transData(l);
handler.sendMessage(msg);
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 100, locationListener);
}Example 66
| Project: ParkenDD-master File: ParkenDD.java View source code |
public Boolean initLocation() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
try {
locationManager.requestLocationUpdates(getProvider(), (long) 60000, (float) 50, locationListener, Looper.getMainLooper());
locationEnabled = true;
return true;
} catch (IllegalArgumentException e) {
e.printStackTrace();
locationEnabled = false;
return false;
}
}Example 67
| Project: PARWorks-Android-MARS-master File: GetLocation.java View source code |
private void searchForLocation() {
final LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
mListener.searchingForLocation();
locationManager.requestLocationUpdates(LocationManager.GPS_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) {
locationManager.removeUpdates(this);
mListener.gotLocation(location);
}
});
}Example 68
| Project: Train-Track-Android-master File: StationsFragment.java View source code |
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_stations, container, false);
ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter(getChildFragmentManager()));
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) v.findViewById(R.id.tabs);
tabsStrip.setViewPager(viewPager);
/*
final Button map = (Button) rootView.findViewById(R.id.map);
map.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent().setClass(getActivity(),
MapActivity.class);
intent.putExtra("all_stations", true);
startActivity(intent);
}
});
*/
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
gps = location;
}
}
};
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, PERMISSIONS_RETURN_CODE);
Utils.log("Requesting location permissions");
} else {
setupLocationListener();
}
return v;
}Example 69
| Project: VectorTileMap-master File: LocationHandler.java View source code |
@Override
public void onLocationChanged(Location location) {
Log.d("LocationListener", "onLocationChanged, " + " lon:" + location.getLongitude() + " lat:" + location.getLatitude());
if (!isShowMyLocationEnabled()) {
return;
}
GeoPoint point = new GeoPoint(location.getLatitude(), location.getLongitude());
if (mSetCenter || isSnapToLocationEnabled()) {
mSetCenter = false;
mTileMap.map.setCenter(point);
}
}Example 70
| Project: android-fourteeners-master File: LocationTest.java View source code |
@LargeTest
public void testCanSetListener() throws InterruptedException {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the gps location provider.
SRLOG.v(TAG, "new location is " + location.toString());
SRLOG.v(TAG, "New location came from: " + location.getProvider());
mNewTestLocation = location;
}
public void onStatusChanged(String provider, int status, Bundle extras) {
SRLOG.v(TAG, "Status Changed " + provider);
}
public void onProviderEnabled(String provider) {
SRLOG.v(TAG, "Provider enabled changed");
}
public void onProviderDisabled(String provider) {
SRLOG.v(TAG, "Provider disabled changed");
}
};
HandlerThread thread = new HandlerThread("LocationTestHandlerThread");
// starts the thread.
thread.start();
Looper mLooper = thread.getLooper();
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListener, mLooper);
Thread.sleep(60000);
Assert.assertTrue("No new location", mNewTestLocation != null);
}Example 71
| Project: AndroidFBPhotoPicker-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 72
| Project: AndroidLibraryProject-master File: LocationDataListener.java View source code |
public Location getLocation(String provider, long minTime, float minDistance, LocationListener locationListener) {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
Log.d(TAG, "No service available to get the location. Network and GPS both are disable or not available");
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
// This line need to be changed
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener); // Now this will be implemented in user level
// Now this will be implemented in user level
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime, minDistance, locationListener);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 60000, locationListener);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}Example 73
| Project: AndroidStudioProjects-master File: MainActivity.java View source code |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datos = (Button) findViewById(R.id.datos);
latitud = (EditText) findViewById(R.id.latitud);
longitud = (EditText) findViewById(R.id.longitud);
resultado = (TextView) findViewById(R.id.resultado);
datos.setOnClickListener(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
/****Mejora****/
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertNoGps();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
} else {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
MostrarLocalizacion(location);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
MostrarLocalizacion(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
/* Datos de los proveedores */
//List<String> listaProveedores = locationManager.getAllProviders();
//LocationProvider proveedor1 = locationManager.getProvider(listaProveedores.get(0));
//int Accuracy = proveedor1.getAccuracy();
//boolean TieneAltitud = proveedor1.supportsAltitude();
/*----*/
/* Establezco criterios para buscar un proveedor */
//Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
//String mejorProveedor = locationManager.getBestProvider(criteria,true);
/*-----*/
}Example 74
| Project: android_external_GmsLib-master File: NativeLocationClientImpl.java View source code |
public void requestLocationUpdates(LocationRequest request, LocationListener listener, Looper looper) {
Log.d(TAG, "requestLocationUpdates()");
if (nativeListenerMap.containsKey(listener)) {
removeLocationUpdates(listener);
}
nativeListenerMap.put(listener, new NativeListener(listener, request.getNumUpdates()));
locationManager.requestLocationUpdates(request.getInterval(), request.getSmallestDesplacement(), makeNativeCriteria(request), nativeListenerMap.get(listener), looper);
}Example 75
| Project: AQUArinthia-master File: BestLocationProvider.java View source code |
private void initLocationListener() {
mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + locationToString(location));
if (isBetterLocation(location, mLocation)) {
updateLocation(location, providerToLocationType(location.getProvider()), true);
if (providerToLocationType(location.getProvider()) == LocationType.CELL) {
if (mCellTimeout != null) {
mCellTimeout.resetTimeout();
}
}
if (providerToLocationType(location.getProvider()) == LocationType.GPS) {
if (mGPSTimeout != null) {
mGPSTimeout.resetTimeout();
}
}
Log.d(TAG, "onLocationChanged NEW BEST LOCATION: " + locationToString(mLocation));
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
mListener.onStatusChanged(provider, status, extras);
}
public void onProviderEnabled(String provider) {
mListener.onProviderEnabled(provider);
}
public void onProviderDisabled(String provider) {
mListener.onProviderDisabled(provider);
}
};
}Example 76
| Project: astrid-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 77
| Project: BeSocial-master File: GeolocationService.java View source code |
@Override
public void onCreate() {
settings = getSharedPreferences("PREFERENCES_FILE", Context.MODE_PRIVATE);
userID = settings.getString("userID", "");
initializeLocationManager();
AWSMobileClient.initializeMobileClientIfNecessary(this);
final DynamoDBMapper mapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER, mapper), new LocationListener(LocationManager.NETWORK_PROVIDER, mapper) };
try {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}Example 78
| Project: Cangol-appcore-master File: LocationServiceImpl.java View source code |
@Override
public void requestLocationUpdates() {
if (null != mLocationListener) {
return;
}
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "location " + location.getProvider() + ":" + location.getLatitude() + "," + location.getLongitude());
if (isBetterLocation(location)) {
mLocation = location;
mServiceHandler.sendEmptyMessage(FLAG_BETTER_LOCATION);
} else {
Log.d(TAG, "location " + location.toString());
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged provider " + provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled provider " + provider);
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled provider " + provider);
}
};
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, mServiceProperty.getInt(LOCATIONSERVICE_GPS_MINTIME), mServiceProperty.getInt(LOCATIONSERVICE_GPS_MINDISTANCE), mLocationListener);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, mServiceProperty.getInt(LOCATIONSERVICE_NETWORK_MINTIME), mServiceProperty.getInt(LOCATIONSERVICE_NETWORK_MINDISTANCE), mLocationListener);
mServiceHandler.sendEmptyMessageDelayed(FLAG_TIMEOUT, mTimeOut);
}Example 79
| Project: cnAndroidDocs-master File: LocationBasedCountryDetector.java View source code |
/**
* Start detecting the country.
* <p>
* Queries the location from all location providers, then starts a thread to query the
* country from GeoCoder.
*/
@Override
public synchronized Country detectCountry() {
if (mLocationListeners != null) {
throw new IllegalStateException();
}
// Request the location from all enabled providers.
List<String> enabledProviders = getEnabledProviders();
int totalProviders = enabledProviders.size();
if (totalProviders > 0) {
mLocationListeners = new ArrayList<LocationListener>(totalProviders);
for (int i = 0; i < totalProviders; i++) {
String provider = enabledProviders.get(i);
if (isAcceptableProvider(provider)) {
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
LocationBasedCountryDetector.this.stop();
queryCountryCode(location);
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
mLocationListeners.add(listener);
registerListener(provider, listener);
}
}
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
mTimer = null;
LocationBasedCountryDetector.this.stop();
// Looks like no provider could provide the location, let's try the last
// known location.
queryCountryCode(getLastKnownLocation());
}
}, getQueryLocationTimeout());
} else {
// There is no provider enabled.
queryCountryCode(getLastKnownLocation());
}
return mDetectedCountry;
}Example 80
| Project: CodenameOne-master File: AndroidLocationManager.java View source code |
public void onLocationChanged(final android.location.Location loc) {
synchronized (this) {
final com.codename1.location.LocationListener l = getLocationListener();
if (l != null) {
Display.getInstance().callSerially(new Runnable() {
@Override
public void run() {
lastLocation = convert(loc);
l.locationUpdated(lastLocation);
lastLocationMillis = SystemClock.elapsedRealtime();
}
});
}
}
}Example 81
| Project: facebook-android-sdk-master File: PickerActivity.java View source code |
@Override
@SuppressLint("MissingPermission")
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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 && checkForLocationPermissionsAndRequest()) {
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);
}
}
}Example 82
| Project: FacebookAnalytics-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 83
| Project: FacebookNewsfeedSample-Android-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 84
| Project: FenceHouston-master File: MainActivity.java View source code |
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "pnJAoPzsbulMxEzSwNLzAdIq1OlgH4NHDnNKdAXl", "I17zOttD1hoS5RErQnboUSoXEbwiXiQX2glcMu4K");
/********** get Gps location service LocationManager object ***********/
//locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/* CAL METHOD requestLocationUpdates */
// Parameters :
// First(provider) : the name of the provider with which to register
// Second(minTime) : the minimum time interval for notifications,
// in milliseconds. This field is only used as a hint
// to conserve power, and actual time between location
// updates may be greater or lesser than this value.
// Third(minDistance) : the minimum distance interval for notifications, in meters
// Fourth(listener) : a {#link LocationListener} whose onLocationChanged(Location)
// method will be called for each location update
//to conantly get user location
/* locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
3000, // 3 sec
10, this);*/
/********* After registration onLocationChanged method ********/
/********* called periodically after each 3 sec ***********/
Button startBtn = (Button) findViewById(R.id.start);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
displayNotification();
}
});
Button cancelBtn = (Button) findViewById(R.id.cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
cancelNotification();
}
});
Button updateBtn = (Button) findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
updateNotification();
}
});
Button mapBtn = (Button) findViewById(R.id.mapBtn);
mapBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//define a new Intent for the second Activity
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
;
}
});
final Button loginBtn = (Button) findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//define a new Intent for the second Activity
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
;
}
});
final Button logoutBtn = (Button) findViewById(R.id.logoutBtn);
logoutBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ParseUser.logOut();
// this will now be null
currentUser = ParseUser.getCurrentUser();
loginBtn.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
});
currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
loginBtn.setVisibility(View.GONE);
logoutBtn.setVisibility(View.VISIBLE);
logoutBtn.setText("Logout of " + currentUser.getUsername());
} else {
// Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
// startActivity(intent);;
}
}Example 85
| Project: findyourfriend-master File: GpsPosition.java View source code |
public void startRecording() {
gpsTimer.cancel();
gpsTimer = new Timer();
setCheckInterval(SettingManager.getInstance().getIntervalUpdatePosition());
setMinDistance(SettingManager.getInstance().getAccuracyUpdatePosition());
// receive updates
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// get now
Location mLocation = getBestLocation();
if (null != mLocation) {
updateToServer(mLocation.getLatitude(), mLocation.getLongitude());
myLocationListener.onMyLocationChanged(mLocation);
}
for (String s : locationManager.getAllProviders()) {
locationManager.requestLocationUpdates(s, getCheckInterval(), getMinDistance(), 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 this is a gps location, we can use it
if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
Toast.makeText(context, "Updating location", Toast.LENGTH_SHORT).show();
doLocationUpdate(location, true);
myLocationListener.onMyLocationChanged(location);
}
}
});
}
// start the gps receiver thread
gpsTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Log.i(TAG, "check!");
Location location = getBestLocation();
doLocationUpdate(location, false);
}
}, 0, getCheckInterval());
}Example 86
| Project: focus-bluetooth-android-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 87
| Project: GeoAlarm-master File: AlarmService.java View source code |
/**
* This function sets up a gps/network location event listener. When location is updated, it checks to see
* if we have reached the destination
*/
private void setLocationListener() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
currentLocation = location;
checkIfAtDestination();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
locationManager.removeUpdates(locationListener);
}Example 88
| Project: GeoPost-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 89
| Project: GTFSOffline-master File: LocationHelper.java View source code |
public void refresh(LocationListener locationListener) {
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_LOCN_UPDATE_TIME, MIN_LOCN_UPDATE_DIST, locationListener);
} catch (final IllegalArgumentException e) {
Log.e(TAG, "Exception requesting location from GPS_PROVIDER");
}
try {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_LOCN_UPDATE_TIME, MIN_LOCN_UPDATE_DIST, locationListener);
} catch (final IllegalArgumentException e) {
Log.e(TAG, "Exception requesting location from NETWORK_PROVIDER");
}
}Example 90
| Project: Home-master File: SetUpActivity.java View source code |
private void setUpLocationMonitoring() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = mLocationManager.getBestProvider(criteria, true);
try {
mLocation = mLocationManager.getLastKnownLocation(provider);
if (mLocation == null) {
mLocationView.setVisibility(View.VISIBLE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Toast.makeText(SetUpActivity.this, R.string.found_location, Toast.LENGTH_SHORT).show();
mLocation = location;
mConfigSettings.setLatLon(String.valueOf(mLocation.getLatitude()), String.valueOf(mLocation.getLongitude()));
mLocationManager.removeUpdates(this);
if (mLocationView != null) {
mLocationView.setVisibility(View.GONE);
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
mLocationManager.requestLocationUpdates(provider, HOUR_MILLIS, METERS_MIN, mLocationListener);
} else {
mLocationView.setVisibility(View.GONE);
}
} catch (IllegalArgumentException e) {
Log.e("SetUpActivity", "Location manager could not use provider", e);
}
}Example 91
| Project: HomeMirror-master File: SetUpActivity.java View source code |
private void setUpLocationMonitoring() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = mLocationManager.getBestProvider(criteria, true);
try {
mLocation = mLocationManager.getLastKnownLocation(provider);
if (mLocation == null) {
mLocationView.setVisibility(View.VISIBLE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Toast.makeText(SetUpActivity.this, R.string.found_location, Toast.LENGTH_SHORT).show();
mLocation = location;
mConfigSettings.setLatLon(String.valueOf(mLocation.getLatitude()), String.valueOf(mLocation.getLongitude()));
mLocationManager.removeUpdates(this);
if (mLocationView != null) {
mLocationView.setVisibility(View.GONE);
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
mLocationManager.requestLocationUpdates(provider, HOUR_MILLIS, METERS_MIN, mLocationListener);
} else {
mLocationView.setVisibility(View.GONE);
}
} catch (IllegalArgumentException e) {
Log.e("SetUpActivity", "Location manager could not use provider", e);
}
}Example 92
| Project: KarungGuniApp-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 93
| Project: life-master File: LocationManagerActivity.java View source code |
@SuppressLint("SetTextI18n")
private void setData() {
this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
/**
* �度
* 纬度
* æµ·æ‹”
*/
Log.i(TAG, "Longitude:" + Double.toString(location.getLongitude()));
Log.i(TAG, "Latitude:" + Double.toString(location.getLatitude()));
Log.i(TAG, "getAltitude:" + Double.toString(location.getAltitude()));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// for ActivityCompat#requestPermissions for more details.
return;
}
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
this.longitudeTV.setText(location.getLongitude() + "");
this.latitudeTV.setText(location.getLatitude() + "");
this.altitudeTV.setText(location.getAltitude() + "");
}
this.getProviders();
this.getBestProvider();
}Example 94
| Project: locationlog-master File: BestLocationProxy.java View source code |
private void updated_requests() {
if (requests.isEmpty()) {
for (LocationListener listener : real_listeners) {
location_mgr.removeUpdates(listener);
}
listening = false;
return;
}
long min_time = 0;
float min_distance = 0;
for (ListenerRequest request : requests) {
if (request.getMinTime() < min_time) {
min_time = request.getMinTime();
}
if (request.getMinDistance() < min_distance) {
min_distance = request.getMinDistance();
}
}
if (listening) {
for (LocationListener listener : real_listeners) {
location_mgr.removeUpdates(listener);
}
}
for (String provider : location_mgr.getProviders(false)) {
Listener listener = new Listener();
real_listeners.add(listener);
location_mgr.requestLocationUpdates(provider, min_time, min_distance, listener);
}
listening = true;
}Example 95
| Project: locationnotifier-master File: LocationService.java View source code |
@Override
public void onCreate() {
super.onCreate();
LocationService.isRunning = true;
preferences = PreferenceManager.getDefaultSharedPreferences(this);
updateRunningNotification();
int lat = preferences.getInt("dest_lat", 0);
int lng = preferences.getInt("dest_lng", 0);
destination = new Location("");
destination.setLatitude(lat / 1E6);
destination.setLongitude(lng / 1E6);
radius = preferences.getFloat("dest_radius", 0);
notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.d(getClass().getSimpleName(), "Location changed");
updateLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
if (preferences.getBoolean("use_gps", false)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
// creepy
Log.d(getClass().getSimpleName(), "Watching your location");
}Example 96
| Project: Lovamimi-For-Android-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 97
| Project: luper-master File: PickerActivity.java View source code |
@Override
protected void onStart() {
super.onStart();
if (FRIEND_PICKER.equals(getIntent().getData())) {
try {
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) {
float distance = location.distanceTo(placePickerFragment.getLocation());
if (distance >= LOCATION_CHANGE_THRESHOLD) {
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) {
String model = Build.MODEL;
if (model.equals("sdk") || model.equals("google_sdk") || model.contains("x86")) {
// this may be the emulator, pretend we're in an exotic place
location = SAN_FRANCISCO_LOCATION;
}
}
if (location != null) {
placePickerFragment.setLocation(location);
placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
placePickerFragment.setSearchText(SEARCH_TEXT);
placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
placePickerFragment.loadData(false);
} else {
onError(getResources().getString(R.string.no_location_error), true);
}
} catch (Exception ex) {
onError(ex);
}
}
}Example 98
| Project: OpenFit-master File: LocationInfo.java View source code |
public static void listenForLocation(final boolean useGeocoder) {
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// locationManager.removeUpdates(this);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
currentAltitude = (float) location.getAltitude();
currentSpeed = location.getSpeed();
if (prevLocation != null) {
Location loc1 = new Location("");
loc1.setLatitude(prevLocation.getLatitude());
loc1.setLongitude(prevLocation.getLongitude());
Location loc2 = new Location("");
loc2.setLatitude(location.getLatitude());
loc2.setLongitude(location.getLongitude());
totalDistance += loc1.distanceTo(loc2);
}
prevLocation = location;
timestamp = location.getTime();
accuracy = location.getAccuracy();
if (useGeocoder) {
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
cityName = addresses.get(0).getLocality();
if (cityName == null) {
cityName = addresses.get(0).getSubAdminArea();
}
if (cityName == null) {
cityName = addresses.get(0).getAdminArea();
}
StateName = addresses.get(0).getAdminArea();
CountryName = addresses.get(0).getCountryName();
CountryCode = addresses.get(0).getCountryCode();
Log.d(LOG_TAG, "onLocationChanged: " + cityName + ", " + CountryCode);
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error: " + e);
}
}
Intent msg = new Intent(OpenFitIntent.INTENT_SERVICE_LOCATION);
msg.putExtra("cityName", cityName);
msg.putExtra("StateName", StateName);
msg.putExtra("CountryName", CountryName);
msg.putExtra("CountryCode", CountryCode);
context.sendBroadcast(msg);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderDisabled(String provider) {
Log.d(LOG_TAG, "GPS OFF");
if (provider.equals(LocationManager.GPS_PROVIDER)) {
Intent msg = new Intent(OpenFitIntent.INTENT_SERVICE_LOCATION);
msg.putExtra("status", false);
context.sendBroadcast(msg);
}
}
@Override
public void onProviderEnabled(String provider) {
Log.d(LOG_TAG, "GPS ON");
if (provider.equals(LocationManager.GPS_PROVIDER)) {
Intent msg = new Intent(OpenFitIntent.INTENT_SERVICE_LOCATION);
msg.putExtra("status", false);
context.sendBroadcast(msg);
}
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 15, locationListener);
//locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, null);
new android.os.Handler().postDelayed(new Runnable() {
public void run() {
Log.d(LOG_TAG, "Location not change: " + cityName + ", " + CountryCode);
if (locationListener != null) {
// locationManager.removeUpdates(locationListener);
if (latitude == 0 && longitude == 0) {
updateLastKnownLocation();
}
}
if (useGeocoder || (cityName != null && CountryCode != null)) {
Intent msg = new Intent(OpenFitIntent.INTENT_SERVICE_LOCATION);
msg.putExtra("cityName", cityName);
msg.putExtra("StateName", StateName);
msg.putExtra("CountryName", CountryName);
msg.putExtra("CountryCode", CountryCode);
context.sendBroadcast(msg);
}
}
}, 20000);
}Example 99
| Project: openmonitor-android-agent-master File: CommunicationService.java View source code |
private void getCurrentLocationGPS() {
locationListenerGPS = new LocationListener() {
@Override
public void onLocationChanged(android.location.Location location) {
Globals.currentLocationGPS = location;
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGPS);
}Example 100
| Project: OsmPointsToMap-master File: MapA.java View source code |
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.thx:
startActivity(new Intent(this, ThxA.class));
break;
case R.id.location:
Toast.makeText(this, "Locate me", Toast.LENGTH_LONG).show();
userGpsRequest = true;
LocationListener locationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
if (location != null && userGpsRequest) {
Log.d("OMS", "Location: " + "lat: " + location.getLatitude() + "lng: " + location.getLongitude());
_mc.setCenter(new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)));
userGpsRequest = false;
_mc.setZoom(16);
mapChanged();
worker.setLocation(location);
}
}
};
if (_lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
_lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
else if (_lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
_lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
break;
case R.id.search:
Toast.makeText(this, "search", Toast.LENGTH_LONG).show();
break;
}
return true;
}Example 101
| Project: otm-android-master File: NearbyList.java View source code |
@Override
public void setupLocationUpdating(Context applicationContext) {
locationManager = (LocationManager) applicationContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lon = location.getLongitude();
update();
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
if (locationManager != null) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_DELAY, 0, locationListener);
setInitialLocation();
}
}