How to use location listener? - android

Its not clear to me how to use the location listener.
Do I do this:
public Location actualLocation;
private class mLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
actualLocation = location;
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
}
//Middle of code
currentLatitude = actualLocation.getLatitude()
currentLongitude = actualLocation.getLongitude()
or this:
public Location actualLocation;
private class mLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
}
//Middle of code
actualLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
currentLatitude = actualLocation.getLatitude()
currentLongitude = actualLocation.getLongitude()
There are variables used that were not declared in this snippets of code. It's on purpose. I shortened the code for the sake of simplicity.
UPDATE:
My question was: ¿Do I use getLastKnow location or do I manually save the location every run be it updates? ¿Would that work the same?

You need to call LocationManager.registerLocationUpdates. You pass the LocationListener into that call, and the framework will call those functions whenever it has a new location.

Related

Getting user location takes a very long time inside Google Map FragmentActivity

I am having issues getting a location in my map activity. Basically, it gets the location, but takes a VERY long time (a few minutes). I'm using a singleton that requests a single location update to retrieve my location. This works fine across multiple other instances in my app. However when I try it in my map activity, it takes a very long time. Here is my class I use to get a location:
public class SingleShotLocationProvider {
public interface LocationCallback {
void onNewLocationAvailable(GPSCoordinates location);
}
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//If network is available
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.i("SingleShot", "network available");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
try {
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(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) {}
}, null);
}
catch (SecurityException e){
Log.e("Location", "security exception");
}
}
//If GPS is enabled
else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Log.i("SingleShot", "GPS available");
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
try {
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(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) {}
}, null);
}
catch (SecurityException e){
Log.e("SingleShot", "security exception");
}
}
else{
Toast.makeText(context, "No network or GPS available. Try again later.", Toast.LENGTH_LONG).show();
}
}
public static class GPSCoordinates {
public float longitude = -1;
public float latitude = -1;
public GPSCoordinates(double lon, double lat) {
longitude = (float) lon;
latitude = (float) lat;
}
}
}
This class works well in most areas in my app. It works in services and fragments. However when I use it in my map activity (FragmentActivity), the singleton takes a long time to use the callback I send it . Here is how I am requesting a new location from my map activity:
public class Traffic extends FragmentActivity
implements OnMapReadyCallback {
MapFragment mapFragment;
GoogleMap map;
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//...
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
SingleShotLocationProvider.requestSingleUpdate(getApplicationContext(), new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
Log.i(TAG, location.toString());
}
});
}
}
Any thoughts on why this would be taking so long?
Try changing the Criteria to COARSE or something which is less accurate but adequate.
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
https://developer.android.com/reference/android/location/Criteria.html

Only call method when object is not null

Lets say that i have an object that asynchronously will be seted (an user GPS position for example).
Is there a way to only call a method in an Activity when this object is not null?
If you simply want to call a method if some object is not null then:
if (myObject != null) { callMyActivityMethod()}
Based on your updated information, you only want to call the method once you have received a location from the GPS.
A LocationListener is used for receiving notifications from your LocationManager.
Create a LocationListener and pass it in your requestForLocationUpdates(). It will then notify you when a new location has been received. For Example:
LocationListener locListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callMyActivityMethod();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
...
requestLocationUpdates(provider, minTime, minDistance, locListener);
...

Android: requestLocationUpdates

I have managed to get a fix on an android device's location (both with network provider and gps provider) using:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
but i would like calculate the phones location at the same moment once using the NETWORK_PROVIDER and then the GPS_PROVIDER so that i can compare each accuracy together.
Does anyone know how to pinpoint the device once with NETWORK_PROVIDER and then with GPS_PROVIDER?
Use 2 Location Listeners
public class MainActivity extends Activity {
private Location networkLocation = null;
private Location gpsLocation = null;
private class NetworkLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// if you only want one location
// if (networkLocation == null)
networkLocation = location;
if (gpsLocation != null) {
// do something
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
}
private class GpsLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// if you only want one location
// if (gpsLocation == null)
gpsLocation = location;
if (networkLocation != null) {
// do something
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
}
}

problems with location manager in maps api v2 android

i'm developping an android app which shows in a map the current location for the user.
Few hours later, i have discovered the error, locationManager doesn't actualize the location.
I put the code relative a locationManager:
mapa = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapaTapas)).getMap();
String serviceString = Context.LOCATION_SERVICE;
LocationManager locationManager = (LocationManager)getSystemService (serviceString);
String proovedor1 = LocationManager.GPS_PROVIDER;
locationManager.getLastKnownLocation(proovedor1);
String proovedor2 = LocationManager.NETWORK_PROVIDER;
locationManager.getLastKnownLocation(proovedor2);
locationManager.requestLocationUpdates(proovedor1, 5000, 5, new LocationListener()
{
#Override
public void onStatusChanged(String arg0, int arg1,Bundle arg2) { }
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onLocationChanged(Location Location)
{
location=Location;
}
});
locationManager.requestLocationUpdates(proovedor2, 5000, 5, new LocationListener()
{
#Override
public void onStatusChanged(String arg0, int arg1,Bundle arg2) { }
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onLocationChanged(Location Location)
{
location=Location;
}
});
location = locationManager.getLastKnownLocation(towers);
if(location != null){
glat = location.getLatitude();
glon = location.getLongitude();
Log.i("location", "latitud: "+glat);
Log.i("location", "latitud: "+glon);
}
cp = new CameraPosition.Builder()
.target(new LatLng(glat, glon))
.zoom(15)
.build();
mapa.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
i need to save in glat and glon the current value of the location and the if it's posibble implement some method to refresh it automatically
There's no need to manually request location updates from LocationManager now that OnMyLocationChangeListener interface was introduced.
You only need to enable the my-location layer (map.setMyLocationEnabled(true)), set the listener (map.setOnMyLocationChangeListener(this)) and do whatever you want with the current location (e.g. animate camera) passed back to you in the corresponding callback (provided by implementing that interface).

LocationManager doesn't update a location

There is the following code for getting current location:
final LocationManager manager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener=new LocationListener() {
#Override
public void onLocationChanged(Location location) {
manager.removeUpdates(this);
Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();
if (location!=null) {
doSomeAction();
}
else {
Toast.makeText(MainActivity.this, LOCATION_IS_NULL_MESSAGE, Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
manager.removeUpdates(this);
String newProvider=provider.equals(LocationManager.GPS_PROVIDER) ? LocationManager.NETWORK_PROVIDER : null;
if (newProvider==null) {
Toast.makeText(MainActivity.this, LOCATION_PROVIDERS_ARE_DISABLED_MESSAGE, Toast.LENGTH_LONG).show();
}
else {
manager.requestLocationUpdates(newProvider, 0, 0, this);
}
}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
String provider=manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ? LocationManager.GPS_PROVIDER :
LocationManager.NETWORK_PROVIDER;
Location location=manager.getLastKnownLocation(provider);
if (location!=null) {
doSomeAction();
}
else {
Toast.makeText(this, "1", Toast.LENGTH_LONG).show();
manager.requestLocationUpdates(provider, 0, 0, listener);
}
I see toast "1" each time, but I've never seen "2" toast, therefore my location isn't be updated. Please, tell me, I need to get my current location - how can I fix my problem? I use network location provider.
Did you actually attach the listener? With out attaching the listener its code is useless, but furthermore afaik: If the LocationManager has no Listener attached it will not update any location.
Try like this :
public class Locato extends Activity implements LocationListener {
LocationManager locman;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.idlayout);
locman = (LocatonManager) getSystemService(Context.LOCATION_SERVICE);
}
public void onStatusChanged(String pr, int s, Bundle a) {}
#Override
public void onProviderDisabled(String provider) {
Log.d("MyApp", "Provider disabled : " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d("MyApp", "Provider enabled : " + provider);
}
#Override
public void onLocationChanged(Location location) {
// do something
}
You must also add permissions to manifest : access coarse location and access fine location

Categories

Resources