I using the new API for get location: android.https://developer.android.com/training/location/retrieve-current.html
Some times when I get the location, It come out of date. I get out at some place and go to another place, then the application returns the first place location to me. It happens when I out the WiFi. When I use the WiFi it works perfectly. Am I missing some method or something else?
public class NewGPSTracker implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener, com.google.android.gms.location.LocationListener {
private LocationRequest lr;
private LocationClient lc;
Location location;
double latitude = 0;
double longitude = 0;
Context context;
static Boolean status = false;
public int res = 0;
boolean conectado;
public NewGPSTracker(Context context) {
this.context = context;
lr = LocationRequest.create();
lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lr.setInterval(5000);
lr.setFastestInterval(1000);
lc = new LocationClient(context, this, this);
}
#Override
public void onLocationChanged(Location location) {
if (conectado) {
lc.removeLocationUpdates(this);
lc.requestLocationUpdates(lr, this);
location = lc.getLastLocation();
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
Log.e("NewGPSTracker", ""+arg0);
}
#Override
public void onConnected(Bundle connectionHint) {
conectado = true;
Log.i("NewGPSTracker", "Google Play Services Conectado.");
lc.requestLocationUpdates(lr, this);
location = lc.getLastLocation();
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public void connect(){
lc.connect();
}
public void disconnect(){
lc.disconnect();
}
#Override
public void onDisconnected() {
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
I exactly don't know what are you using. But when i use google API for this situation, solved a issue like that.
Now line that at top always uses HIGH_ACCURACY of GPS/WI-FI. And your situation it looks like WI-FI always.. As you know there are two method to find user's location. (GPS/WI-FI) when you change your GPS location and not opening your WI-FI it should keep showing first.
So try to change it as a static variable like GPS, if it's possible.
Sorry for my bad english, complicated situation..
Calculate the difference of the time stamp of the location to the current time.
If it is more than some seconds, it is an old positoin, e.g the last known.
In that case wait for the next position, untill time difference is less than some seconds.
Related
I have written a GPS code using location listener for capturing latitude and longitude of a current location and it is working fine for most of my devices.
But some devices( particularly Samsung ) is not able to load this latitude longitude from location listener.
This is the code i have used continuously changing latitude and longitude.
public class MyLocationListner implements LocationListener {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String getLatitude = "" + location.getLatitude();
String getLongitude = "" + location.getLongitude();
double x = location.getLatitude();
double y = location.getLongitude();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
To call above location listener i am using below piece of code in my activity.
emphasized text
{LocationManager location_manager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new MyLocationListner();
location_manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, listner);
}
Please give the solution why it is not working.
Thanks in advance
I created a class to use the LocationListener but I am getting classCastException when I request for location updates
This is my class code
public class Loc implements
LocationListener, GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
// A request to connect to Location Services
private LocationRequest mLocationRequest;
// Stores the current instantiation of the location client in this object
private LocationClient mLocationClient;
/*
* Note if updates have been turned on. Starts out as "false"; is set to
* "true" in the method handleRequestSuccess of LocationUpdateReceiver.
*/
boolean mUpdatesRequested = false;
// Milliseconds per second
public static final int MILLISECONDS_PER_SECOND = 1000;
// The update interval
public static final int UPDATE_INTERVAL_IN_SECONDS = 10;
// A fast interval ceiling
public static final int FAST_CEILING_IN_SECONDS = 1;
// Update interval in milliseconds
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// A fast ceiling of update intervals, used when the app is visible
public static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* FAST_CEILING_IN_SECONDS;
Location currentLocation ;
LocationListener locListener;
Context x;
public Loc(Context con) {
// Create a new global location parameters object
this.x=con;
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new LocationClient(con, this, this);
}
public void stop() { // If the client is connected
if (mLocationClient.isConnected()) {
stopPeriodicUpdates();
}
// After disconnect() is called, the client is considered "dead".
mLocationClient.disconnect();
}
public void start() {
mLocationClient.connect();
}
public void startUpdates() {
mUpdatesRequested = true;
startPeriodicUpdates();
}
public Location getLocation() {
// Get the current location
currentLocation = mLocationClient.getLastLocation();
// Display the current location in the UI
Log.e("lat log", "" + currentLocation.getLatitude() + " , "
+ currentLocation.getLongitude());
return currentLocation;
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
currentLocation=location;
Log.e("lat log", "" + currentLocation.getLatitude() + " , "
+ currentLocation.getLongitude());
}
#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
}
private void stopPeriodicUpdates() {
mLocationClient
.removeLocationUpdates((com.google.android.gms.location.LocationListener) this);
}
private void startPeriodicUpdates() {
mLocationClient.requestLocationUpdates(mLocationRequest,(com.google.android.gms.location.LocationListener) this);
}
}
This is my activity code
public class MainActivity1 extends Activity {
Loc l;
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
t=(TextView)findViewById(R.id.txt);
l = new Loc(getApplicationContext());
l.start();
}
public void getLoc(View v) {
// l.getLocation();
l.startUpdates();
}
I am getting my lat and long perfectly fine.
But my issue is with for location updates
I get this error
Caused by: java.lang.ClassCastException: com.example.gps.Loc cannot be cast to com.google.android.gms.location.LocationListener
I do get that I cannot pass LocationListener like this
mLocationClient.requestLocationUpdates(mLocationRequest,(com.google.android.gms.location.LocationListener) this);
But how should I exactly pass it??
Only needed to add the interface
com.google.android.gms.location.LocationListener
like this.
public class Loc implements
GooglePlayServicesClient.ConnectionCallbacks
,GooglePlayServicesClient.OnConnectionFailedListener
,com.google.android.gms.location.LocationListener {
//...
}
Here is what I need to do. I need to launch my application and on the click of a button, I need to display the current coordinates, that is latitude and longitude. I followed this tutorial and used the following code for my purpose:
public class MainActivity extends Activity {
public double latitude;
public double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
final TextView latValueLabel = (TextView)findViewById(R.id.latLabel);
final TextView lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#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
}
}
(Copy pasted only a part of the code, please ignore any unclosed brackets or anything like that.)
It continuously gets the latitude longitude as location changes and stores it to two double variables latitude and longitude and when the setButton is clicked, it displays the last stored lat-lon value. That would be the user's current location. Now the issue is, I launched the app and while still staying on the exact location from which the app is launched, I clicked the Set Button. But at that time the location is not changed, so the latitude and longitude are displayed as zero, which is the default value of the double variables. I need to take a walk around with the device so that the location is changed before I can get my actual coordinates. How can I get the lat-lon as soon as the app is launched?
You can use getLastKnownLocation(...) to initialise the longitude and latitude values like this:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
This is your total class.
public class MainActivity extends Activity {
public double latitude;
public double longitude;
private TextView latValueLabel,lonValueLabel ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
latValueLabel = (TextView)findViewById(R.id.latLabel);
lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
I'm working on an Android project which give the user the possibility to turn on his GPS. His position is requested to launch the application.
After activation, I use getLastKnownLocation of LocationManager but this method returns a Location indicating the data from the last known location fix obtained from the given provider. The doc explains that 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.
However the user activate localization services. So turn on the GPS is not enough to launch the GPS as it's done by Google Maps by showing an icon at the top of the device and retrieving GPS coordinates. This icon doesn't appear when my application gives the user the possibility to activate the GPS (seems weird).
Theards I already read use getLastKnownLocation method after choosing the best provider. Questions are did I miss something after turning on the GPS services? Did the GPS is automatically launch when the GPS is activated?
I already ask this, but not enough answer.
for showing blue dot icon on map use this line
map_fragment.setMyLocationEnabled(true);
use this code to get location where you want to get location
GPSTracker gps = new GPSTracker(this);
Double latiDouble = gps.getLatitude();
Double loDouble = gps.getLongitude();
create a class GPSTracker and add this code
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10; //10 meters
private static final long MIN_TIME_BW_UPDATES=1000*60*1; //1 minute
private LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext=context;
getLocation();
}
public Location getLocation()
{
locationManager=(LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
//showSettingAlert();
}
else
{
this.canGetLocation=true;
if(isGPSEnabled)
{
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
}
if(locationManager != null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
if(locationManager!=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
return location;
}
public void stopUsingGPS()
{
if(locationManager!=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location != null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location != null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingAlert()
{
AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled .Do you want to go to settings menu ?");
alertDialog.setPositiveButton("Settings",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent i=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(i);
}
});
alertDialog.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
No, turning on GPS is not enough, you also need a Location Listener to listen to updates of position.
Something like in Location Strategies
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.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 network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
I've implemented code that should return present location.
First the code:
public static double[] getLocation(Context context) {
double[] result;
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
MyLocationListener ll = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
while(!hasLocation) { }
result = ll.getResult();
return result;
}
private static class MyLocationListener implements LocationListener {
double[] result = new double[2];
public double[] getResult() {
return result;
}
#Override
public void onLocationChanged(Location location) {
if(location.getAccuracy() != 0.0 && location.getAccuracy() < 100) {
result[0] = location.getLatitude();
result[1] = location.getLongitude();
hasLocation = true;
lm.removeUpdates(this);
}
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
The problem is that all stopps on 'while' statement. WHen I've tried to debug this setting breakpoint on the first line in onLocationChanged() nothing happens, but Logcat was showing some logs like:
loc_eng_report_position: vertical_accuracy = 64.000000
DEBUG/libloc(1292): date:2011-08-11, time:10:51:03.372, raw_sec=1313052663, raw_sec2=1313052663,raw_msec=1313052663372
Any ideas?
The while(!hasLocation) {} is blocking your application from doing anything. You'll either need to deal with the location in the callback onLocationChanged, or you'll need to start the location manager a lot earlier and hope that you have a result by the time you need it. You can't busy-wait for the answer.