How To Get Device Location?
I am using openweathermap to parse weather information, it works fine without the city, but when I try to fetch city, it force closes. How do I fix this? been searching for hours b
Solution 1:
Please find attached code for fetching location using LocationManager
.
private GoogleApiClient mGoogleApiClient;
private Context mContext;
@SuppressWarnings({"MissingPermission"})publicvoidgetLocation(Context context) {
mContext = context;
LocationManagerlocationManager= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
// getting GPS statusbooleanisGPSEnabled= locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network statusbooleanisNetworkEnabled= locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
//Show message alert for gps enable
} else {
mGoogleApiClient = newGoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
}
After that, you will get callback on onConnected method and you get location from there
@OverridepublicvoidonConnected(@Nullable Bundle bundle) {
Locationlocation= LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (location != null) {
double lat= location.getLatitude();
double lang= location.getLongitude());
} else {
//No location found message
}
mGoogleApiClient.disconnect();
}
Post a Comment for "How To Get Device Location?"