Android Location Services Not Updating requestLocationUpdates - android

I have a simple class GPSListener which gets the GPS coordinates:
public class GPSListener implements LocationListener {
public static double latitude;
public static double longitude;
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
} ...
Then trying to make use of this class in my activity, I simply invoke the class in my onCreate() function in my activity:
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new GPSListener();
Criteria criteria = new Criteria();
String bestProvider = mlocManager.getBestProvider(criteria, false);
mlocManager.requestLocationUpdates(bestProvider, 0, 0, mlocListener);
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
lat = GPSListener.latitude;
lon = GPSListener.longitude;
Log.d("GPS", "lat: "+lat+" long:"+lon);
} else {
// TODO: GPS not enabled
Log.d("GPSERROR", "GPS not enabled");
}
But whenever I run the application, lat and lon in my activity are always zero. I'm not quite sure how to get around this issue.
When logging:
Log.d("GPSLISTENER ", "lat: "+latitude+" long:"+longitude);
It returns the correct latitude and longitude, it just takes a second or two after the activity starts.
Log.d("GPSSUCCESS", "lat: "+lat+" long:"+lon);
Just returns 0.0 for both. I was under the impression that .requestLocationUpdates would pass the value to lat and lon before the if statement is executed. How can I accomplish this?

You are using public static field for latitude, longitude.
Please change it to non static and using setter, getter with instant object:
lat = mlocListener.getLatitude();
lon = mlocListener.getLongitude();

Google updated its location handling logic. It is now easier to listen location updates with fused location provider. You can implement your location listener in 5 min. Take a look.
Methods for getting the most accurate location
You are listening only gps provider and it is not ready(on waiting for location status) yet and then it does not return any location. Just take a look at fused location provider and write your location listener again.

try this...
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
return false;
}
});
user this Handler to get Location
private Handler customHandler = new Handler();
private Runnable updateTimerThread = new Runnable() {
#Override
public void run()
{
try
{
Location myLocation = mGoogleMap.getMyLocation();
secndLocationListener.onLocationChanged(myLocation);
}
catch (Exception e)
{
Log.getStackTraceString(e);
}
}
};
to run this
customHandler.postDelayed(updateTimerThread , 1000);

LocationManager uses the last known location from the cache. The cache is updated when you load google maps. Try this out, go out in the open and check your location. Move to a different location about 200m and check your location again. It will be same as the old one. Now, load google maps, you will notice that you application magically now has the new location.
You need to programmatically kick that cache to the latest location. The only way to do that is
YOUR_APPLICATION_CONTEXT.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_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(final Location location) {
}
});

Related

Android | Google Maps Getting Current Location and Update

I am trying to get my current location on map and update it when I move. Every time when an update happens, I want to get current longtidude and latitute values to use in other methods.
private LocationRequest request = LocationRequest.create().setInterval(50000);
I think I have to use LocationRequest . I created an object which will update its location every 5 minutes. But now I don't have any idea how to use it. I checked tutorials on internet but they are so complicated for a beginner. Does anybody have simple solution?
EDIT
This is how my code looks now :
public class MainActivity extends Activity implements LocationListener {
private GoogleMap map;
public double latitude;
public double longitude;
private LocationManager locationManager;
private Context mContext;
private android.location.LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
getLocation();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
public void getLocation()
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
}
}
When I tried to test it, my app stopped working. Since this is my first android app and I am not very good at it, I couldn't find whats wrong.
for location use this
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
longitude = "0.00";
latitude = "0.00";
}
}
}
from http://androidadvance.com/android_snippets.php#h.r43fot3suy6h
use gps to determine location ( longtidude and latitute values ) and pass it to maps
this mainactivity.java for gps
public class GpsBasicsAndroidExample extends Activity implements LocationListener {
private LocationManager locationManager;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_basics_android_example);
text=(TextView)findViewById(R.id.tv1);
/********** get Gps location service LocationManager object ***********/
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/*
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
*/
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,10, this);
/********* After registration onLocationChanged method called periodically after each 3 sec ***********/
}
/************* Called after each 3 sec **********/
#Override
public void onLocationChanged(Location location) {
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
//Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
text.setText(str);
}
#Override
public void onProviderDisabled(String provider) {
/******** Called when User off Gps *********/
Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
/******** Called when User on Gps *********/
Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
and this for maps
main.java
enter code here
public class MainActivity extends FragmentActivity {
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
Marker ciu = mMap.addMarker(new MarkerOptions()
.position(CIU).title("My Office"));
final LatLng CIU1 = new LatLng(30.21843892856462, 33.41662287712097);
Marker ciu1 = mMap.addMarker(new MarkerOptions()
.position(CIU1).title("My Second Office"));
final LatLng CIU2 = new LatLng(30.21843892856462, 30.41662287712097);
Marker ciu2 = mMap.addMarker(new MarkerOptions()
.position(CIU2).title("My thired Office"));
}
}
Here is how you can do. I will try to make it simple for you:
Add LocationListener interface to your extended activity class using implements keyword. This will force you to Override some methods you will need to find your current location.
public class A extends Activity implements LocationListener {}
Create an instance of the Location Manager class which would act as a hook to call various services and methods in Location package.
private LocationManager locationManager;
Create a method like getLocation() and call the predefined service method from the Location Manger instance.
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
In the onLocationChanged() method you can request the latitude using getLatitude() and longitude using getLongitude() using these two methods that are the part of Location Manager class.
Store the two values obtained by these methods in two separate variables make sure they are of Double type, later you can convert them in String type and then display them on a Text view of your app activity.
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
Call the getLocation() method in your onCreate() and display them on app screen by having a TextView or a toast.
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
Last but not the least dont forget to add permissions in you Manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Fore more details please refer to this link.

How to get the new latitude and longitude cordinates from android

How i am getting location details:
AppLocationService appLocationService = new AppLocationService(getApplicationContext());
Location nwLocation= appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);
nwLocation.getLatitude();
nwLocation.getLongitude();
What is happening since my code has llast known location .... its giving me the last location that was updated say now its evening. its giving me the location updated during morning
What i want:: how can i make a fresh network request to get the current location at my position
AppLocationService.java
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 0;
private static final long MIN_TIME_FOR_UPDATE = 0;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Your code is registering to receive location updates and also returns the last known location. What happens is expected because you didn't wait to receive an updated one.
Once the method "onLocationChanged" was called by the system you'll have the new one. You can then send a broadcast from the service.
You are trying to get the current location in a synchronous mode which is not possible as it takes some time to lookup the updated one.
The primary reason why you aren't getting updated location information quickly is that you're relying on the NETWORK_PROVIDER.
You should instead use this
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
How to call Explicitly onLocationChanged
public void locationlist()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
50, 0, this);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {}
if(location == null)
{
}
else{
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
}
}
now call the method locationlist where you want like in a timer.
Use onLocationChanged method and get the longitude and latitude from the parametr location
Code:
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = new Location(location);
latitude=mCurrentLocation .getLatitude();
longitude=mCurrentLocation .getLongitude();
}

Get current latitude and longitude in the string

I am trying to get latitude and longitude but sometime network is available but I am not getting value of latitude and longitude. I am using MyLocationListener class and put condition all but some time value is not getting.
protected void showCurrentLocation()
{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
counter++;
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude=location.getAltitude();
}
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
counter++;
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude=location.getAltitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle b)
{
}
#Override
public void onProviderDisabled(String s)
{
}
#Override
public void onProviderEnabled(String s)
{
}
}
Here Best way to get Longitude Latitude:
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(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 network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "changed Loc : "+longitude + ":"+latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if(isGPSEnabled){
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "Loc : "+longitude + ":"+latitude);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}else
{
/*
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
*/
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}else
{
longitude = "0.00";
latitude = "0.00";
}
}
}
if device is not able to get currentLocation using GPS then it'll be take fron NetworkProvider or else it'll take 0,0 as my requirement but you can modify as per your requirement
May it'll helpful to you.
Happy Coding :D
See, this is a very common problem. In order to have exact Latitude and Longitude ,You must use GPS also it must me activated on the mobile device but GPS too have some limitations. GPS works most efficiently under open sky. you will not have a clear range inside a building. So try your code under open sky and check the response.

Unable to get latitude and longitude from android

getLastKnownLocation always return null value. I have enabled geo fix and gps on emulator. However, there is no gps signal on the notification bar when running this on emulator. May I know is there any mistake in my code? Thanks.
public void onCreate(Bundle savedInstanceState) {
LocationManager location = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.near_layout);
location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
String bestProvider = location.getBestProvider(criteria, true);
LocationListener ll = new mylocationlistener();
Location loc = location.getLastKnownLocation(bestProvider);
if(loc != null)
{
double latitude = loc.getLatitude();
double longitude = loc.getLongitude();
Toast.makeText(nearPlace.this, " nice" + latitude, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(nearPlace.this, "Location not available. GPS is not enabled.", Toast.LENGTH_LONG).show();
}
location.requestLocationUpdates(bestProvider, 0, 0, ll);
}
private class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Toast.makeText(nearPlace.this, " nice" + location.getLatitude(), Toast.LENGTH_LONG).show();
nearPlaceDownloaderTask getNearPlace = new nearPlaceDownloaderTask();
getNearPlace.execute(ANDROID_WEB_LINK + "gt.php?la=" + location.getLatitude() + "&lo=" + location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
The reason your code is not working, is because you have specified the following criteria:
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
Android will prefer to use network location over GPS, because you don't care about the accuracy. By specifying an accuracy of 20 meters or so, it will probably automatically invoke GPS.
To manually invoke GPS location updates, override bestProvider:
bestProvider = LocationManager.GPS_PROVIDER;
You can really simplify this into two lines of code:
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, interval,
precision, listener);
Don't forget to unregister your listener:
locationManager.removeUpdates(listener);
You might also want to check this out geofix not working
Also make sure you have mock locations allowed set in the emulator. Take a look at Pauls answer as well, which is why I was asking in comments what provider was returned

In ANDROID, How to get a current position and tracking in map using GPS without giving any location in a program?

I am new to android, can anyone help me for my question....
How to get a current position and tracking in map using GPS without giving any location in a program?????
You want the easy way out ! Use MyLocationOverlay object. you can get the current location by calling the method getLastFix(); . To enable tracking use enableMyLocation(). To add this object to the map you need to add it to your map overlays.
MyLocationOverlay currLoc=new MyLocationOverlay(context,mapKey);
mapView.getAllOverlays.add(currLoc);
currLoc.enableMyLocation();
Location myLastLocation=currLoc.getLastFix();
currLoc.enableCompass();
Do make sure, in onPause() you do this :
currLoc.disableMyLocation(); //to save battery.
you can resume updates in onResume() by calling currLoc.enableMyLocation();
This is the easiest way I could find! and it is quite accurate too
Try ;
String m_BestProvider;
LocationManager m_LocationManager;
LocationListener m_LocationListener = null;
Location m_Location = null;
m_LocationManager = (LocationManager) m_Context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
m_BestProvider = m_LocationManager.getBestProvider(c, false);
// Define a listener that responds to location updates
m_LocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
m_LocationManager.requestLocationUpdates(m_BestProvider, 0, 0, m_LocationListener);
m_Location = m_LocationManager.getLastKnownLocation(m_BestProvider);
Systme.out.println(m_Location.getLatitude() "," +m_Location.getLongitude());
Add in AndriodManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
public class GPSLocationBased extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationbased);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new Mylocationlistener();
// ---Get the status of GPS---
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS is not enable then it will be on
if(!isGPS)
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
}
//<--registers the current activity to be notified periodically by the named provider. Periodically,
//the supplied LocationListener will be called with the current Location or with status updates.-->
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
/**
*Mylocationlistener class will give the current GPS location
*with the help of Location Listener interface
*/
private class Mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// ---Get current location latitude, longitude, altitude & speed ---
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
float speed = location.getSpeed();
double altitude = location.getAltitude();
Toast.makeText(GPSLocationBased.this,"Latitude = "+
location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)

Categories

Resources