Location Not Update in ANdroid - java

I want to get Mobile Current Location ,When I install Application ,than first time get correct lat long but than after every time display first time get location.please give me correct code for get every time correct lat long.
_ In Sort My Location is Not Update,or Location cach not clear.
->my code
public class MyLocationListener implements LocationListener {
private LocationManager mLocationManager;
private Location currentLocation;
public MyLocationListener(Context context) {
mLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
currentLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, this);
}
public Location getBestLocationAvailable() {
return currentLocation;
}
#Override
public void onLocationChanged(Location newBestLocation) {
mLocationManager.removeUpdates(this);
currentLocation = newBestLocation;
}
#Override
public void nProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
MyLocationListener loc = new MyLocationListener(MainActivity.this);
Location location = loc.getBestLocationAvailable();
system.out.println(location.getLatitude()+" "+location.getLongitude);
give me write answer,why i get ever time old lat Long?

Try to get latitude and longitude inside the onLocationChnage()
public void onLocationChanged(Location loc) {
//sets and displays the lat/long when a location is provided
String lat = loc.getLatitude();
String longt= loc.getLongitude();
Toast.makeText(getApplicationContext(),"Lat"+ lat+ "Long"+longt, Toast.LENGTH_LONG).show();
}
Add the permission in menifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />

You code looks right, but why did you add this string?
mLocationManager.removeUpdates(this);
So, you will receive only one location update and after it your listener will be disabled. Try to remove this string and check again.
Also, please note that different devices take different time for GPS "cold" start. Before testing your app, check GPS status in another app (for example maps, or GPS monitor). If your device on "cold" state, you will not receive any updates long time (10-20 minutes or more).

Related

FusedLocationProviderClient returns wrong latitude and longitude

Following the examples from google developers site, I use FusedLocationProviderClient to get de last known location.
private FusedLocationProviderClient fusedLocationClient;
// ..
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
And on button click, I call:
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
myposition.setText(location.getLatitude() + ", " + location.getLongitude());
// ...
}
}
});
But, sometimes, it gives me a location that is far from current device geoposition. I've checked it on three different devices. I have declared:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
How should I use fusedlocation to get the best position with accuary? I've tried to change getlastlocation with getcurrentlocation but this last method is not available, although the docs said it is available.

Android: Google Maps myLocation button - perform zoom in

I'm intercepting the click from the mylocation button like so:
map.setMyLocationEnabled(true);
map.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
bMyLocationClicked = true;
return false;
}
});
and then making it zoom in like so:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) parentActivity.getSystemService(Context.LOCATION_SERVICE);
LocationListener myLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (bMyLocationClicked) {
bMyLocationClicked = false;
map.moveCamera(CameraUpdateFactory.zoomTo(18f));
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, myLocationListener);
Everything works fine, except that there's an extremely long delay between pressing the mylocation button and the zoom in actually happening. The centering of the map finishes and about 2 seconds later the map actually zooms in. How can I speed this up?
I'm looking for an answer where I stay using the mylocation button rather than implementing my own.. although, if there's absolutely no alternative, I'll build a custom center/zoom button.

Fused Location Provider not getting location unless GPS is on

So I have implemented the new Fused Location Provider API to get a location of the user but for some reason, I cannot get any location unless the GPS is on. Not always, will users have their GPS on and I would like to not have to ask them to turn their GPS on every time the load the app.
How can I tell the API to give me a location with whatever provider it has available?
Here is my code:
public class FusedLocationService implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
public interface OnLocationChangedListener {
public void OnLocationChanged(Location location);
}
private final String TAG = "SE8611";
private boolean mRequestingLocationUpdates = true;
private OnLocationChangedListener mCallBack;
Service locationService;
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private Location mCurrentLocation;
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
public FusedLocationService(Service locationService, final long INTERVAL, final long FASTEST_INTERVAL) {
Logger.log(TAG, "FusedLocationService called");
this.mCallBack = (OnLocationChangedListener)locationService;
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
this.locationService = locationService;
googleApiClient = new GoogleApiClient.Builder(locationService)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
if(mRequestingLocationUpdates) {
startLocationUpdates();
}else{
Logger.log(TAG, "Location updates are already running.");
}
}
protected void startLocationUpdates() {
this.fusedLocationProviderApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
this.mRequestingLocationUpdates = false;
}
#Override
public void onLocationChanged(Location mCurrentLocation) {
Logger.log(TAG, "onLocationChanged called");
this.mCurrentLocation = mCurrentLocation;
this.mCallBack.OnLocationChanged(this.mCurrentLocation);
}
public void startLocationUpdatesAfterResume(){
if (googleApiClient.isConnected() && !mRequestingLocationUpdates) {
Logger.log(TAG, "startLocationUpdatesAfterResume called");
this.startLocationUpdates();
}
}
public void stopLocationUpdates() {
Logger.log(TAG, "stopping Location Updates");
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
}
public Location getLocation() {
return this.mCurrentLocation;
}
#Override
public void onConnectionSuspended(int i) {
this.mRequestingLocationUpdates = true;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
this.mRequestingLocationUpdates = true;
}
}
I had the same issue like you, which is not an issue at all.
Android used to have a GPS button that let you control it directly, but they replaced it with a Location button which works different.
In order to get any type of location, you must turn it on.
Like you, I thought the Location button turns on and off the GPS only, but that's not the case.
You can control the GPS by changing the location mode:
1. High accuracy (GPS, Wi-Fi and mobile networks)
2. Power Saving (Wi-Fi and mobile networks)
3. GPS only
I think I have found the solution of the problem.
If you go to Settings -> Privacy and Safety -> Location, you would notice that Location is not only GPS, but it actually lets user decide which providers can be used. For example, you can set that only WiFi and Cellular should be used to obtain any locations
Disabling Location option will disable all providers at once, not only GPS.
To test that app for users with only WiFi can get a location – change setting to "Wifi+Cellular".
you seem to be using LocationRequest.PRIORITY_HIGH_ACCURACY, which prefers using GPS above and over other methods. You might want to use PRIORITY_BALANCED_POWER_ACCURACY, which will use WiFi and cell towers before using GPS.
Also, since PRIORITY_BALANCED_POWER_ACCURACY is a "coarse" level of accuracy, you might want to change the location permission in your manifest appropriately.
The training documentation details more information about the priority flags, you might also want to go through it.

Execute async method inside onLocationChanged()

I have a class which extends from AsyncTask and gets data in JSON format from a web service. My android app has to retrieve data asynchronously whenever the location is changed. My android activity implements LocationListener and I am invoking the asynchronous execution in onLocationChanged() method. I have tried setting zero for both minTime and minDistance parameters of requestLocationUpdates() method but the data which is to be retrieved asynchronously is never retrieved.
The code for my onCreate() and onLocationChanged() methods is given below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
}
#Override
public void onLocationChanged(Location location) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLatitude());
new MyAsyncTask().execute();
}
The latitude and longitude variables are used in the MyAsyncTask class for getting data with respect to user's current location.
Please tell me what's wrong with my code. I have been looking for the solution since last week but haven't found any.
oke, a little bit confused but let me understand it. You retrieve the data in onLocationChanged() ? example long=111 lat=222 and with your Asyntask you make a GET request to a WS with a json parameter probably long and lat and some other stuff in it ? and if you try to debugg it there are some values in logcat ? or some error ? or did you put the permision in the manifest file ? or in the phones settings ?
did tried debugging??
or
Log??
are you getting any error???
sometimes the location.getLatitute() and location.getLatitute() returns null which may cause null pointer Exception..
that may stopped reaching the MyAsyncTask()
check this may help you..
#Override
public void onLocationChanged(Location location) {
double latit =null;
double longi =null;
do
{
latit=location.getlatitude();
longi=location.getlongitude();
}while(latit!=null && longi!=null);
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLatitude());
new MyAsyncTask().execute();
}
The getlatitude() and getlongitude() function will return double value check this documentation
http://developer.android.com/reference/android/location/Location.html#getLatitude()
Oops My Bad!
The correct code is
#Override
public void onLocationChanged(Location location) {
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
new MyAsyncTask().execute();
}

Application never received a GPS fix

We have a strong GPS signal I have an app for testing how fast a GPS lock can be established I even tested the navigation app on my phone they all get pretty much insta lock bellow 10 if I just turned on the GPS.
But with this app I just never get a lock, the wile loop just keeps going on and on and the Log never shows I let it run for 10min and nothing. Am I missing something here I know there is a possible > 10min delay but other apps have no problem that are not using lastKnownLocation but pulling an actual location.
Also the gpsLocation() method is in a static Locator class.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Location location = Locator.gpsLocation(this);
while(location == null)
{
location = Locator.gpsLocation(this);
}
Log.w("GPS LOCATION", "LOCATION FOUND");
}
/**
* Finds users location using gps
* satelite network.
*
* #param FragmentActivity
* #return Location
*/
public static Location gpsLocation(FragmentActivity context)
{
// Fetch LocationManager service & instance of UserLocator
LocationManager provider = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
UserLocator locator = new UserLocator();
// Attempt to get a fix on users location
provider.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locator);
// Return users location using GPS Service
return locator.location;
}
/**
* Use to listen for user location updates
* TODO: Reimplement as a anonymous class
*/
class UserLocator implements LocationListener
{
// Public accessor
public Location location;
public void onLocationChanged(Location location)
{
if(location != null)
{
// We have a fix on users location
this.location = location;
}
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
I think your problem is that your location updates listener is updating the location variable inside your UserLocation class, however the variable you are checking is the one you get back from the method gpsLocation, which is null.
What you are doing is you are signing up for location updates and immediately returning the value of null and checking it over and over again, while your real location is being updated in another place.
All this is also assuming that you have declares the proper permission in your manifest file.
Try this:
Location location;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gpsLocation(this);
while(location == null)
continue;
Log.w("GPS LOCATION", "LOCATION FOUND");
}
public static void gpsLocation(FragmentActivity context)
{
LocationManager provider = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
UserLocator locator = new UserLocator();
provider.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locator);
}
class UserLocator implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc != null)
location = loc;
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
With this implementation, both the listener and the while loop address the same instance of Location, so once this changes from null you will get the log message.
I would however strongly discourage putting such a while(true) loop in your onCreate method, you will be blocking the main thread, and this is generally a bad thing to do.

Categories