Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Activity
public static final int REQUEST_CODE = 123; LocationManager mLocationManager; LocationListener mLocationListener;
@Override protected void onResume(){ super.onResume(); getCurrentLocation(); }
private void getCurrentLocation() { Log.d("Clima", "getWeatherForCurrentLocation"); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { Log.d("Clima", "onLocationChanged"); String longitude = String.valueOf(location.getLongitude()); String latitude = String.valueOf(location.getLatitude()); Log.d("Clima", "longitude is: " +longitude); Log.d("Clima","latitude is: " + latitude); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); return; } mLocationManager.requestLocationUpdates(LOCAION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener); }
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); Log.d("Clima", "onRequestPermissionsResult"); if (requestCode == REQUEST_CODE) { if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ getCurrentLocation(); } } }