Get user current lat lng after GPS enabled - Android - android

I have followed this tutorial http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/ for showing popup if GPS in not enabled and getting users current location.
And here is the broadcast receiver which listens to the GPS enabled disabled condition
private BroadcastReceiver mGpsSwitchStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
gps = new GPSTracker(getActivity());
if(gps.canGetLocation()){
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
Toast.makeText(getActivity(), "GPS Switch", Toast.LENGTH_SHORT).show();
if(gps.getLatitude() != 0 && gps.getLongitude() != 0 ){
final CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(gps.getLatitude(),gps.getLongitude())) // Sets the center of the map to selected place
.zoom(15) // Sets the zoom
.build(); //
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Toast.makeText(getActivity(), "GPS Switch Lat: "+gps.getLatitude()+" Long: "+gps.getLongitude(), Toast.LENGTH_SHORT).show();
}
} else {
if(!gps.isSettingDialogShown())
gps.showSettingsAlert();
}
}
}
};
When I enable the GPS via settings dialog or from drop down menu. GPSTracker class gets the location service and checks for the user's current location in this code fragment
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 Enabled");
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", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
return location;
}
Problem:
Firstly I don't know why broadcast receiver, receives the action two times and secondly when in normal mode lat lng value in receiver remains zero but in debugging sometimes it returns the value of users current location.
Can you please help what I am doing wrong?

If you don't need to work with Gps and Network Locations separately. I recommend to use FusedLocationProvider. BroadcastReceiver is probably working twice because it works for both gps and network location services

Related

Location is null even if GPS is turned on

I am working on google maps. I want to get the user location and show him on the map. I wrote a Locationlistener to get the user location.
public Location getUserLocation(){
try {
// 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
return null;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,DISTANCE_CALC,TIME_UPDATE, this);
Log.d("Network", "Network Enabled");
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,DISTANCE_CALC,TIME_UPDATE, this);
Log.d("GPS", "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;
}
The getUserLocation() is one of the functions in the LocationListener that will return the user location with either the GPS or the network. I am calling this function from a fragment like this.
if (Build.VERSION.SDK_INT >= 23){
if (checkPermission()) {
location = locHandler.getUserLocation();
if(location!=null)
showTheMaps(location);
else
AlertBuilder(title,body);
}else {
requestPermission();
}
}else {
//The build is less than marshmellow so no need for permission
location = locHandler.getUserLocation();
try {
// double d = location.getLatitude();
showTheMaps(location);
}catch (NullPointerException e){
AlertBuilder(title, body);
}
}
public void showTheMaps(Location location){
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()), DataModel.zoomlevel);
googleMap.animateCamera(cameraUpdate);
}
The AlertBuilder function will show an alert box with a button which upon click closes the app.
As you can see from the screenshot the GPS is enabled yet the location returned to me is null and the app closes after showing the alert dialog.
What could be the problem? why is the location returning null even after turning on the GPS?
Use
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
Source: https://developer.android.com/training/location/retrieve-current.html
Another (deprecated) way is to set a OnMyLocationChangeListener to your map to get the location
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
// do something with location
}
});
More info: how to get current location in google map android

Locationhandler does not return Location with Samsung Galaxy

I've created a location tracker application who send the location of a mobile device to a database.
When I test the location with my old samsung device (without a SIM) the application works. He sends the locationmanager and sends it to the db.
But when I test the application with my newer device. A samsung Galaxy. The application does not work. It can't calculate the location because he says 'GPSisenabled' is false and 'NetworkedEnabled' is also false..
Here's my code to determine the location. Maybe someone has a answer to this strange thing, thanks
public Location getLocation() {
try {
ConfigurationManager();
if (isGPSEnabled == false && isNetworkEnabled == false) {
// no network provider is enabled
return null;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
location = null;
Log.d("Network", "Network - GET LOCATION ");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
location = null;
if (location == null) {
Log.d("GPS Enabled", "GPS Enabled - GET LOCATION");
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;
}
You should use FusedLocationProviderApi for getting the current location as per android documentation. Read more here : Getting the Last Known Location

some devices do not return current latitude longitude

I am trying to get the address of the user, for that i need the current latitude and longitude of the user. I am using following code for the same
public LatLng getCurrentLocation(Context context) {
try {
LocationManager locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String locProvider = locMgr.getBestProvider(criteria, false);
Location location = locMgr.getLastKnownLocation(locProvider);
// getting GPS status
boolean isGPSEnabled = locMgr
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNWEnabled = locMgr
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNWEnabled) {
Log.v(TAG, "Network and GPS are unavailable");
// no network provider is enabled
return null;
} else {
// First get location from Network Provider
if (isNWEnabled) {
Log.v(TAG, "Network is enabled for getting the location");
if (locMgr != null) {
Log.v(TAG,
"Location manager is not null so fetch the location from network");
location = null;
location = locMgr
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
if (locMgr != null)
location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
return new LatLng(location.getLatitude(), location.getLongitude());
} catch (NullPointerException ne) {
Log.e(TAG, "Current Lat Lng is Null");
return new LatLng(0, 0);
} catch (Exception e) {
e.printStackTrace();
return new LatLng(0, 0);
}
}
In my Moto e with android 4.4 it is working very good but in some of the devices it does not return the lat lng and i get 0,0 which is returned in the exception.
What i need to change to get it correct in all devices.

Switch between GPS_PROVIDER and NET PROVIDER when device is stationary for a period of time in Android

I'm writing a GPS Tracker which I use for getting the location of the device every minute. I use both GPS_PROVIDER and NET_PROVIDER to get the location, but sometimes, the location is not getting updated even though I'm moving the device for a long time.
So I'm thinking:
If the location is not changing for a period of time with a certain provider, switch to another provider and check for new location again.
Is this correct?
Here's my getLocation code:
public Location getLocation(Context context) {
this.mContext = context;
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) {
// no network provider is enabled
this.canGetLocation = false;
Log.d("DMCAILOCATION","DMCAILOCATION: can not get location");
} else {
this.canGetLocation = true;
//=======================
Location location=null;
Location locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNet = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.d("DMCAILOCATION","DMCAILOCATION: locationGPS:"+locationGPS + "locationNet:"+ locationNet );
if ( locationGPS != null ) {
location= locationGPS;
latitude = location.getLatitude();
longitude = location.getLongitude();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
getLocationnet();
Log.d("DMCAILOCATION","DMCAILOCATION: get by gps");
}
else {
location= locationNet; locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
latitude = location.getLatitude();
longitude = location.getLongitude();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
getLocationgps();
Log.d("DMCAILOCATION","DMCAILOCATION: get by net");
}
Log.i("DMCAILOCATION","NetLocationTime:" + locationNet.getTime() + "locationGPS.getTime(): " +locationGPS.getTime());
Log.d("DMCAILOCATION","DMCAILOCATION: LAT: "+latitude+", "+longitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}

getLatitude() , getLongitude() returns wrong latitude and longitude values

This is the code i use to find my current location but it is not pointing the location accurately, it returns a location as 9.920473,78.102423 instead of 9.909076, 78.100758
I could not figure it out where i am going wrong , please help me with suggestions.
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);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
Log.e("latitude", ""+latitude);
Log.e("longitude", ""+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);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
Log.e("latitude", ""+latitude);
Log.e("longitude", ""+longitude);
}
}
}
}
}
You are using Network Provider first, which is not very accurate. If you get a location fix from Network your code wont use GPS location. In this case, this much variation in the location is to be expected. If you need exact location, use GPS Provider.
Try with this code:
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();
}

Categories

Resources