In an app I am working on I am getting the GPS coordinates of the device inside the activity's onCreate() method. However, even after launching the app, I see the location services icon that keeps flashing in the notifications bar of the device, it this expected or should it go away after getting the position of the device?
This is my code at the moment:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_DENIED)
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
Criteria criteria = new Criteria();
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(lm.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
// Get latitude and longitude
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
You are never telling LocationManager to stop providing location updates. To do that, call LocationManager.removeUpdates() with the correct listener as argument.
Alternatively, you can use LocationManager.requestSingleUpdate(...) which automatically stops providing updates after the first location.
Related
I want to get my current latitude and longitude using Mobile network provider, not GPS. AKA it should work without GPS with just your sim card. i have found many tutorials online claiming they find location with gps or network. however, they all seem to use GPS only! here or here and also here i don't want last knows location, as i don't wish to use GPS
Try This Code you can get current location without opening GPS
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
Do it via 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.NETWORK_PROVIDER, 0, 0, locationListener);
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) {
}
});
This is my code. Please tell me y it is not able to calculate the distance.. In this code res is a long variable which is supposed to store the total distance covered. This code is supposed to calculate distance based on GPS as soon as there is a change in the latitude and longitude..
String serviceString = Context.LOCATION_SERVICE;
LocationManager locationManager;
locationManager= (LocationManager)getSystemService(serviceString);
String provider = LocationManager.GPS_PROVIDER;
final Location loc1=locationManager.getLastKnownLocation(provider);
//Location loc1=new Location("");
String netprovider=LocationManager.NETWORK_PROVIDER;
lat1=loc1.getLatitude();
lon1=loc1.getLongitude();
LocationListener myLocationListener = new LocationListener()
{
public void onLocationChanged(Location loc1)
{
Location loc2=new Location("");
lat2=loc2.getLatitude();
lon2=loc2.getLongitude();
dtvalue.setText(lat1+","+lon1+","+lat2+","+lon2);
Location.distanceBetween(lat1,lon1,lat2,lon2,dist);
res=res+(long)dist[0];
lat1=lat2;
lon1=lon2;
}
public void onProviderDisabled(String provider)
{
// Update application if provider disabled.
}
public void onProviderEnabled(String provider)
{
// Update application if provider enabled.
}
public void onStatusChanged(String provider, int status,
Bundle extras)
{
// Update application if provider hardware status changed.
}
};
locationManager.requestLocationUpdates(provider, 5000, 1, myLocationListener);
locationManager.requestLocationUpdates(netprovider, 5000, 1, myLocationListener);
The problem that you are defining an empty location Location loc2=new Location(""); and then using it.
You can define lat1 and lon1 in your class.
public void onLocationChanged(Location loc1)
{
if(lat1 != 0 && long1 != 0) {
Location.distanceBetween(lat1,lon1,loc1.getLatitude(),loc1.getLongitude(),dist);
res+=(long)dist[0];
}
lat1=loc1.getLatitude();
lon1=loc1.getLongitude();
}
When I run my app on Android 4.2 OS phone, I can't seem to be able to get any values returned from getLAstKnownLocation ( always null )
The weird thing is that the Mapview works fine and it shows me my current location !!
Any ideas how to solve this issue ?
here is my code
in onCreate:
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = mlocManager.getBestProvider(criteria, false);
mlocManager.requestLocationUpdates(provider, 0, 0, geoHandler);
then the listener:
public class GeoUpdateHandler implements LocationListener {
public void onLocationChanged(Location location) {
// called when the listener is notified with a location update from the GPS
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
new GeoPoint(lat, lng);
Log.d(this.getClass().getSimpleName(), "onLocationChanged " + lat);
// mlocManager.removeUpdates(this);
}
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
Log.d(TAG, "DISABLED");
}
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
Log.d(TAG, "ENABLED");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the status of the GPS provider changes
Log.d(TAG, "CHANGED");
}
}
getLastKnownLocation will return a null when the provider is disabled. Or when there is no LastKnownLocation.
On the line: provider = mlocManager.getBestProvider(criteria, false);
your provider is asking for the BestProvider including disabled providers. Try using true at the end of the statement and see if that works.
http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation(java.lang.String)
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