Reputation: 543
How to get the Location only through GPS without any kind of Internet connection. I use the below code to get the location but not working without the internet. Please let me know why I'm not getting the location without internet
boolean isGPSEnabled = manager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = manager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
// First get location from Network Provider
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (manager != null) {
location = manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (manager != null) {
location = manager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
}
}
}
Log.d(TAG, "getLocation: "+currentLatitude+" "+currentLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 0
Views: 102
Reputation: 5052
Firstly, the code scope you pasted is famous, it's combination of last known locations of network and GPS providers. Even getLastKnownLocation
methods are called just after requestLocationUpdates
methods, this usage is fully not trusted. Because those sensors won't give result in sync way.
You have two options, one is to call getLastKnownLocation
to get last obtained location for GPS, and second is to make location request with requestLocationUpdates
. Choosing this, will be determined by your scenario.
Upvotes: 1
Reputation: 870
Use this short code to get lattitude and Longitude with only GPS
LocationManager manager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d("Location = ","Longitude "+location.getLongitude()+",Latitude "+location.getLatitude());
Upvotes: 0