I use these code to get location
But sometime I cannot get the location inside building, and that time the WIFI is connected, Location is enabled.
How can I make sure getLastKnownLocation will return location when it is able to get location?
LocationManager locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(location==null)
{
Toast.makeText(getApplicationContext(),"no location", Toast.LENGTH_SHORT).show();
return;
}
This works for me...
public void updateLoction(View view){
locationManger = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManger.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
txtLat.setText("" + location.getLatitude());
txtLon.setText("" + location.getLongitude());
}
locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
private void setLocation(Location location) {
if (location != null) {
txtLat.setText("" + location.getLatitude());
txtLon.setText("" + location.getLongitude());
}
locationManger.removeUpdates(this);
}
Related
I have the following function for retrieving latitude and longitude of the current location of the mobile.
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double latti = location.getLatitude();
double longi = location.getLongitude();
lattitude = String.valueOf(latti);
longitude = String.valueOf(longi);
textView.setText("Your current location is" + "\n" + "Lattitude = " + lattitude
+ "\n" + "Longitude = " + longitude);
} else {
Toast.makeText(this, "Unable to Trace your location", Toast.LENGTH_SHORT).show();
}
}
}
This function is being called through a button. The problem is that by clicking the button the function doesn't seem to find the location and keep on toasting the same message which is toasted in the else statement. Can someone please point out that what is it that i am doing wrong.
First you need to define a LocationListener
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
//your code here to get lat lon from location
}
And in the activity
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
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
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
I'm trying to get GPS Longitude & Latitude.
Everything is working in case that the GPS is turning on while using any other program that turning it on.
But when i trying to use only my app , the GPS is not turning on.
here is my code:
m_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = m_locationManager.getBestProvider(m_c, false);
Location location = m_locationManager.getLastKnownLocation(provider);
if (location != null)
{
double lng = location.getLongitude();
double lat = location.getLatitude();
gpsLocationLon.setText("" + lng);
gpsLocationLat.setText("" + lat);
}
else
{
gpsLocationLon.setText("No Provider");
gpsLocationLat.setText("No Provider");
}
public void onLocationChanged(Location location) {
double lng = location.getLongitude();
double lat = location.getLatitude();
if(null != gpsLocationLat && null != gpsLocationLon)
{
gpsLocationLon.setText("" + lng);
gpsLocationLon.setText("" + lat);
}
}
what did i miss?
You need to start listening to location updates once you've found the best provider.
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider, 0, 0, this);
// ^^ This will start listening for location updates
// depending on your provider.
} else {
Log.d(LOGTAG, provider + " not enabled");
}
Remember that there are two types of providers, gps and network. So it depends on the criteria(m_c) which one is selected.
If you want to make sure that you want to listen to GPS as well as Network Updates, remove the Criteria variable and try this :
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
} else {
Log.d(LOGTAG, "network provider not enabled");
}
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} else {
Log.d(LOGTAG, gps provider not enabled");
}
Edit 1:
m_locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (m_locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
m_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location location = m_locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
else {
Log.d(LOGTAG, "network provider not enabled");
}
if (m_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
m_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else {
Log.d(LOGTAG, "gps provider not enabled");
}
if (location != null)
{
double lng = location.getLongitude();
double lat = location.getLatitude();
gpsLocationLon.setText("" + lng);
gpsLocationLat.setText("" + lat);
}
else
{
gpsLocationLon.setText("No Provider");
gpsLocationLat.setText("No Provider");
}
public void onLocationChanged(Location location) {
double lng = location.getLongitude();
double lat = location.getLatitude();
if(null != gpsLocationLat && null != gpsLocationLon)
{
gpsLocationLon.setText("" + lng);
gpsLocationLon.setText("" + lat);
}
}
I have a problem to fixed position. I use getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
but always return null, i have set the permissions in your AndroidManifest.xml.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
and enabled in Settings --> Location and Security --> location through network.
TextView locationShow = (TextView) this.findViewById(R.id.location);
double latitude = 0.0, longitude = 0.0;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
else {
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
Log.i("SuperMap", "Location changed : Lat: " + location.getLatitude() + " Lng: " +
location.getLongitude());
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
locationShow.setText("经度:" + latitude + "纬度:" + longitude);
I find that other apps can show the location correctly, so maybe there something wrong with my code.
getLastKnownLocation() give the last valid cached location.
You are trying to get the cached location from the Network Provider. You have to wait for a few minutes till you get a valid fix. Since the Network Provider's cache is empty, you are obviously getting a null there.