I'm trying to make an application which gives current location to the user if GPS is On and shows an AlertDialog if not and asks for turning On the GPS.
But the method returns NULL only either GPS is On or Off... How can I solve it? I've looked for solution here and here but it didn't help.
Below is the getLocation()
method that I'm using
public Location getLocation() {
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
Toast.makeText(this,"using gps",Toast.LENGTH_LONG).show();
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();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If we are reaching this part, it means GPS was not able to fetch
// any location
// Getting network status
isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Toast.makeText(this,"using network",Toast.LENGTH_LONG).show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions((Activity)getBaseContext(), new String[] {
android.Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_ACCESS_COURSE_LOCATION );
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// return TODO;
}
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If reaching here means, we were not able to get location neither
// from GPS not Network,
if (!isGPSEnabled) {
Toast.makeText(this,"turn on gps",Toast.LENGTH_LONG).show();
// so asking user to open GPS
askUserToOpenGPS();
}
} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}
I have referred the above code from the answer to one of the above mentioned links.