I am developing android application using the Location. I am able to get the current location using following code.
public void GetLocation()
{
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private LocationManager mLocationManager;
private String mProvider;
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGPSEnabled && isNetworkEnabled)
{
mProvider = mLocationManager.getBestProvider(criteria, false);
Location location = mLocationManager.getLastKnownLocation(mProvider);
Sring mLatitude=String.valueOf(arg.getLatitude());
String mLongitude=String.valueOf(arg.getLongitude());
}
}
I need to update the location of the user in background, once the location is changed not frequently. How can I achieve this?
public class CurrentLatLng implements LocationListener {
public static final int GPS_NOT_ENABLED = -1;
public static final int VALID = 1;
LocationManager manager;
Context context;
public CurrentLatLng(Context context) {
this.context = context;
}
public void getCurrentLatLng() {
//Check if GPS is enabled
if (Commons.isGPSEnabled(context)) {
manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10, 10, this);
} else {
// GPS NOT ENABLED. EVEN THEN THE LOCATION WILL BE RECIEVED AS WE ARE GETTING LOCATION BY NETWORK_PROVIDER
}
}
#Override
public void onLocationChanged(Location l) {
// HERE YOU WILL GET THE LATEST LOCATION AND WILL BE UPDATING WHENEVER YOU CHANGE YOUR LOCATION.
}
}
You need to use location listener. You can listen the location in specific meters or specific time interval. Check this tutorial.
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
**MINIMUM_TIME_BETWEEN_UPDATES**,
**MINIMUM_DISTANCE_CHANGE_FOR_UPDATES**,
new MyLocationListener()
);
Related
I'm trying to get user coordenates in my app, it's a worker tracking app. My locationManager is started as a service to keep tracking when the activity is closed.
Service:
public class ServiceGPS extends Service implements LocationListener {
private Context mContext;
protected LocationManager locationManager;
private int MIN_DISTANCIA_MOVIDA = 5;
private int MIN_TEMPO = 20;
private int QUALIDADE_HORIZONTAL = 2;
private int QUALIDADE_VERTICAL = 2;
private String provider;
public ServiceGPS() {}
#Override
public void onStart(Intent intent, int startId) {
mContext = getApplicationContext();
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
if (verificaGpsNetwork(locationManager)) {
iniciaGPS();
}
else {
showSettingsAlert();
}
}// onStart
public void iniciaGPS() {
Criteria criteria = new Criteria();
criteria.setHorizontalAccuracy(QUALIDADE_HORIZONTAL);
criteria.setVerticalAccuracy(QUALIDADE_VERTICAL);
criteria.setAltitudeRequired(false);
provider = locationManager.getBestProvider(criteria, true);
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider, MIN_TEMPO, MIN_DISTANCIA_MOVIDA, this);
}
else
showSettingsAlert();
}// iniciaGPS
public void onLocationChanged(Location location) {
registraLocalizacao(location);
}// onLocationChanged
}
It works fine in 5.0.2, but location always comes NULL in 4.4.2.
Is there a problem using GPS provider as a service? With
provider = locationManager.getBestProvider(criteria, true);
provider returns GPS, and the GPS icon does keep showing (even with the aplication closed, so the service seems to be OK), but never returns any location, and if I try to use
locationManager.getLastKnownLocation(provider)
always comes back NULL. In the other hand if I just set my provider as 'network' the onLocationChanged is called with the coordenates.
So, whats up with that? Any work around on that?
I wrote a program that provides the user's position with in a building but not the actual position . I Know that Gps does not provide high accurate result with in building . My code is as follows:
public class Internet extends Service implements LocationListener {
Context context;
LocationManager locationManager;
public Internet(Context context) {
this.context = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
}
Location findMeInternet() {
Boolean isInternet = false;
Location location;
isInternet = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isInternet) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 3, 1, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return location;
}
}
return null;
}
//other override methods with empty bodies .
}
Try GPS provider instead of NetWORK provider ,
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
Make sure that device GPS is enabled. (If someone needs to downvote, please mention the reason also)
my code is here:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(false);
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
It only get coordinate when I connected to internet.
You can use android GPS service to get Longitute and Latitute too,
add the permission in your AndroidMenifest.xml,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Initialization,
// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;
// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;
// Declaring a Location Manager
protected LocationManager mLocationManager;
// This is constructor to get System Location services,
public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
Checking if GPS managed to fetch the data,
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
public void getUserLocation() {
Location location;
TextView lon = (TextView) findViewById(R.id.textView2);
TextView lat = (TextView) findViewById(R.id.textView3);
boolean GpsEnable = false, NetworkEnabled = false;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// String locationProvider = LocationManager.GPS_PROVIDER;
GpsEnable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
NetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// locationManager.requestLocationUpdates(locationProvider,0,0,locationListner);
if (!GpsEnable && !NetworkEnabled) {
Toast.makeText(getBaseContext(), "No Provider Availabe",
Toast.LENGTH_SHORT);
} else {
if (NetworkEnabled)
Toast.makeText(getBaseContext(), "Network Provider Available",
Toast.LENGTH_SHORT);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lon.setText("Latitude" + location.getLatitude());
lat.setText("Longitude " + location.getLongitude());
}
if (GpsEnable) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lon.setText("Latitude" + location.getLatitude());
lat.setText("Longitude " + location.getLongitude());
}
}
}
}
}
I had done both with GPS and network provider.. I want to know how we get exact current location in Google maps? Is there any way or algorithm by which i can get longitude and latitude of my location using internally Google maps?
Thanks in Advance
I have Followed this Tutorial for Fast Update and Initial SetUp for GoogleMap v2
Initial Setup Here
Alternative for LocationUpdate
Hope this could help...:)
public void retriveLocation(){
try {
String locCtx = Context.LOCATION_SERVICE;
LocationManager locationmanager = (LocationManager) context.getSystemService(locCtx);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationmanager.getBestProvider(criteria, true);
locationmanager.requestLocationUpdates(provider, 0, 0, this);
} catch (Exception e) {
}
}
Hope this code can be useful for retrieving fast location updates.
Here is the code that I basically use to get a constant location signal using Google Play Services.
public class MyActivity
extends
Activity
implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener
{
private LocationClient locClient;
private LocationRequest locRequest;
// Flag that indicates if a request is underway.
private boolean servicesAvailable = false;
#Override
protected void onCreate( Bundle savedInstanceState )
{
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
servicesAvailable = true;
} else {
servicesAvailable = false;
}
if(locClient == null) {
locClient = new LocationClient(this, this, this);
}
if(!locClient.isConnected() || !locClient.isConnecting())
{
locClient.connect();
}
// Create the LocationRequest object
locRequest = LocationRequest.create();
// Use high accuracy
locRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locRequest.setInterval(INTERVAL);
locRequest.setFastestInterval(INTERVAL);
}
#Override
public void onLocationChanged( Location location )
{
// DO SOMETHING WITH THE LOCATION
}
#Override
public void onConnectionFailed( ConnectionResult arg0 )
{
}
#Override
public void onConnected( Bundle arg0 )
{
// Request location updates using static settings
locClient.requestLocationUpdates(locRequest, this);
}
#Override
public void onDisconnected()
{
if(servicesAvailable && locClient != null) {
//
// It looks like after a time out of like 90 minutes the activity
// gets destroyed and in this case the locClient is disconnected and
// calling removeLocationUpdates() throws an exception in this case.
//
if (locClient.isConnected()) {
locClient.removeLocationUpdates(this);
}
locClient = null;
}
}
}
This is the crux of it anyway and I culled this from other sources so I can't really claim it but there it is.
I'm trying to get the latitude and longitude and below is class which does that...
But i get android runtime exception at
Location l = locMgr.getLastKnownLocation(bestProvider);
and at longt = Double.toString(loc.getLongitude());
Also provider is always shown as DummyLocationProvider even on the phone
public class Util implements LocationListener {
public static LocationManager locMgr;
private static List<String> providers;
private static String bestProvider;
private Context context;
public static String lat;
public static String longt;
public Util(Context context) {
this.context = context;
if(locMgr == null) //Get LocationManager
locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void getLocations() {
//List All providers
providers = locMgr.getAllProviders();
//Get criteria
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//Get best provider
bestProvider = locMgr.getBestProvider(criteria, false);
printProvider(bestProvider);
//Get Last known location
Location l = locMgr.getLastKnownLocation(bestProvider);
if(l==null)
System.out.println("im null");
printLocation(l);
}
private void printLocation(Location loc) {
if(loc == null) { //means there is no recent location
getNewLocation();
}else
lat = Double.toString(loc.getLatitude());
longt = Double.toString(loc.getLongitude());
System.out.println("cached " + lat + " " + longt);
}
private void printProvider(String provider) {
System.out.println(provider);
LocationProvider info = locMgr.getProvider(provider);
System.out.println("provider= " + info.toString() + "\n\n");
}
private boolean getNewLocation() {
if(locMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //This is executed since it can get locations faster than gps (is executed only if use wireless networks for locations is selected)
locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
return true;
}else if(locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) { //This is exceuted if n/w locations is turned off & gps is turned on
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return true;
}else { //executed when gps & location by network is turned off..
return false;
}
}
Please modify your code, it may help you..
Location l = context.locMgr.getLastKnownLocation(bestProvider);