Android GPS using old locations - android

Im trying to learn more about location services in android and am attempting to build an app which can locate an Android device and send it's latitude and longitude to a server. I've had everything working as expected for a while, but am still being bothered by a small bug. When I send the command from the server to locate the device the first time, the device returns a recent, but old, location such as a road I drove on the same day.
On the second time the device receives a command from the server to locate the device, the device returns an accurate location.
Here is the relevant code:
LocationTracker.java
public class LocationTracker extends Service implements LocationListener {
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10*1000; //10,000 meters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 10000; // 10,000 minutes
//Declaring a Location Manager
protected LocationManager locationManager;
public void fetchLocation(Context context) {
getLocation(context);
if (canGetLocation())
{
String stringLatitude = String.valueOf(latitude);
String stringLongitude = String.valueOf(longitude);
Log.i("Location: ", stringLatitude + " " + stringLongitude);
new MyAsyncTask().execute(stringLatitude, stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
Log.i("Error: ", "Cannot get location");
}
}
public Location getLocation(Context context)
{
try
{
locationManager = (LocationManager) context.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
}
else
{
this.canGetLocation = true;
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
//If no GPS, get location from Network Provider
if (isNetworkEnabled && !isGPSEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(LocationTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location)
{
double newLat = location.getLatitude();
double newLong = location.getLongitude();
String stringNewLatitude = String.valueOf(newLat);
String stringNewLongitude = String.valueOf(newLong);
Log.i("New Location: ", stringNewLatitude + " " + stringNewLongitude);
new MyAsyncTask().execute(stringNewLatitude, stringNewLongitude);
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public IBinder onBind(Intent intent)
{
return null;
}
Why is my location updating as an old location the first time it tries, and a correct location on the second time?
Also note that I would also like to remove requestLocationUpdates seen here:
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
because it causes a handler on dead thread warning, but when I removed it my device stopped acquiring my location. This may be part of the problem.
I would greatly appreciate any help!

It's because you're using getLastKnownLocation().
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
getLastKnownLocation(String Provider) :
Returns a Location indicating the data from the last known location fix obtained from the given provider.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

Related

Android getLocation on install app is 0.0

im testing my app in a real device, and a get a error and dont know how to fix.
My app asks for permission to location on android, when install the application asks to allow access.
To locate the position the first time you need to click on the location button.
My problem is this: If GPS is disabled, the app does not find the right position, even after activation, getting as latitude and longitude 0.0.
When you click the button the app checks if it is activated and asks to activate, but even activating the location is the same as 0.0
If you install the app with GPS enabled, this problem does not occur.
Can someone help me?
im using this code to location button
public void btnlocalizacao(View view) {
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
CameraPosition newCamPos = new CameraPosition(new LatLng(latitude, longitude),
15.5f,
googleMap.getCameraPosition().tilt, //use old tilt
googleMap.getCameraPosition().bearing); //use old bearing
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(newCamPos), 2000, null);
} else {
gps.showSettingsAlert();
}
}
and this is the gps class
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 ; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
Criteria criteria = new Criteria();
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
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
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
//location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("Localização", latitude + " " + longitude);
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
//location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("Localização", latitude + " " + longitude);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("ALerta de GPS");
// Setting Dialog Message
alertDialog.setMessage("GPS não esta ativado, gostaria de ativar?");
// On pressing Settings button
alertDialog.setPositiveButton("Configurações", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#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;
}
}
My problem is this: If GPS is disabled, the app does not find the right position, even after activation, getting as latitude and longitude 0.0.
It is all works as intended. The fact you are granted location permission means you are permitted to obtain the location IF and only IF it is available. It means nothing more, especially it does NOT guarantee nor even mean that you will ever get any coordinates from the system (user may i.e. simply do not use GPS receiver).

Not gettting accurate location in some android phones

I have used below code. It work fine but in some devices like Redme,Asus not getting accurate location.It shown me too far from my current location aprox 20 km away.Not getting where is problem somebody have idea please share there ideas.Thanks in advance.
public class Currentlocation extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
public boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
SetOnLocationFoundListner OLF;
public interface SetOnLocationFoundListner {
public void onLocationFound(Location location, boolean getLocRegularly, GoogleMap gmap);
}
public Currentlocation(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
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
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(Currentlocation.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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 IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
*/
}
You can not expect the phone neither to always have a valid "last known location" nor to define its location in microseconds.
You first call requestLocationUpdates() and instantly after that getLastKnownLocation(). There's no time for the phone to determine/update the "last known location". Besides now you always call requestLocationUpdates() again and again when you call getLocation(). Just call it once when you want to start receiving location updates.
Just subscribe to receive location updates once and always get the latest location in the callback that happens with a small delay. You already have the empty onLocationChanged() method. That is the callback method. Just make that to handle the location updates.
You can of course call removeUpdates() or removeLocationUpdates() once you have received the fresh and up-to-date location in the onLocationChanged() callback if you don't want to receive any further updates.
Some useful Stackoverflow discussions:
How to get location that isn't out of date?
Android: getLastKnownLocation out-of-date - how to force location refresh?
Android - Reliably getting the current location

Android location is always null with both NETWORK_PROVIDER and GPS_PROVIDER

This the Service class that I'm trying to use from my MainActivity.java. Running on emulator.
package com.example.sonia.project;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker() {
}
public Location getLocation(Context mContext) {
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
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
Log.d("Location", "Location changed!");
this.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;
}
}
This is my onStart() method of MainActivity
#Override
protected void onStart() {
super.onStart();
gps = new GPSTracker();
gps.getLocation(this);
}
And then I call getLocation() again on a button click in MainActity
gps.getLocation(this);
The accepted answer on this question suggests getting location updates and using multiple providers - My current location always returns null. How can I fix this?. I'm doing both.
getLocation() always returns a null location, even if I try to get the location after several minutes. What can do to make it return a valid location and not null?
To get Location in emulator you have to configure through emulator control
For more information refer following link
http://wptrafficanalyzer.in/blog/android-gps-with-locationmanager-to-get-current-location-example/

Location only refreshes when I turn GPS off

So I have a problem when trying to resolve my location. When given the command to find my location, it instead gives me the last location of where I turned my GPS off. Being able to find my coarse location using WiFi also seems to not be working.
Here is my current class
public class LocationTracker extends Service implements LocationListener {
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//Declaring a Location Manager
protected LocationManager locationManager;
public void fetchLocation(Context context) {
contextnormal = context;
getLocation(context);
if (canGetLocation())
{
String stringLatitude = String.valueOf(latitude);
String stringLongitude = String.valueOf(longitude);
Log.i("Location: ", stringLatitude + " " + stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
Log.i("Error: ", "Cannot get location");
}
}
public Location getLocation(Context context)
{
try
{
locationManager = (LocationManager) context.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
}
else
{
this.canGetLocation = true;
//First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(LocationTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location)
{
//Want to Execute Asynctask method to HTTP post the lat and long. Is there a way `to pass in a context to do this?`
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
if (contextnormal != null) {
fetchLocation(contextnormal);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
I would guess the problem lies in these lines
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
And for some reason it is giving the last known location as the last time the GPS was turned on. Any ideas as to why it is doing that instead of giving the last known location as the present location if the GPS is on?
EDIT:
Implementing the following method and testing:
#Override
public void onLocationChanged(Location location)
{
double newLat = location.getLatitude();
double newLong = location.getLongitude();
String stringNewLatitude = String.valueOf(newLat);
String stringNewLongitude = String.valueOf(newLong);
new MyAsyncTask().execute(stringNewLatitude, stringNewLongitude);
}
You can't just query the location manager for its last known location repeatedly, that will only get you the last known location. It sounds like what you are trying to do is get location updates as you move around.
In this case, you will need to register for location updates, as you tried with your line:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
You are on the right track here, but what is this (the last argument on the function call [yes I know it is a reference to the current class...])? The last argument is supposed to be an intent or a callback where the updates will be broadcast to. It doesn't appear that you have implemented that from the code you provided.
Change your this argument to a class which implements LocationListener. The location updates will come to the onLocationChanged method where you can then process them as you see fit. A simple way to do this is to add a nested inner class which implements the listener, then you can just create an instance of that class and pass it to the location manager, in place of your current this argument.
EDIT
OK, so you are implementing the thing correctly, but blisfully ignoring the location updates, don't do that. The service you have is a Context -- so you can pass that around as you see fit, although it may be better to use:
this.getApplicationContext();
If you are passing it to some long running thing. What I would recommend is to queue your location updates when the arrive in onLocationChanged(). After queuing the location, signal a background worker thread (or AsyncTask) to actually post the location to your web service.
Also, don't override onBind and return null. Just don't override it.

onLocationChanged only called once, not update automatically

In android app want to get the location by button click here is my code
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
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
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
public void onLocationChanged(Location location) {
this.location=location;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
and my call function that get the Latitude,Longitude from above code.
double lat = gps.getLatitude();
double log = gps.getLongitude();
but its only give the same location even the place is changed.
any one help me...thanks in advance..
I looked in your code and it seems correct in all way. Can you please try it by making minimum distance to 0 as you have given min. distance 10 meter and may be you didn't moved at that much rate and your service may be taking min. distance as primary point instead of min. time.
#Dynamo: requestupdatelocation call the onLocationChanged callback method. It is not totally depending on the location assignment. location value will change as per the user location updates.
Here question is that "onLocationChanged" callback method is not getting call on given parameter.
Try this
public void onLocationChanged(Location location) {
this.location = location;
}
and also try reducing the MIN_DISTANCE_CHANGE_FOR_UPDATES to a least value.
Your code seems correct. The only reason I could think of is that device is not able to get the locations. It takes a few minutes for the device to get a lock on your location so try giving it some time.
You can use adb shell dumpsys location to check which apps have a location listener registered and if your app is among them. It will also tell you when was the last time android got a location update. Also try running any other location app to see if this problem is with your app or the environment.

Categories

Resources