I'd like to know why I can not use GPS_PROVIDER
. It works with NETWORK_PROVIDER
, but I need GPS
.
public class MainActivity extends AppCompatActivity {
private TextView textLati, textLong, textCidade, textEstado, textPais, textRua;
private LocationManager locationManager;
private Address endereco;
private final int REQUEST_LOCATION = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLati = (TextView) findViewById(R.id.txtLatitude);
textLong = (TextView) findViewById(R.id.txtLongitude);
textCidade = (TextView) findViewById(R.id.txtCidade);
textEstado = (TextView) findViewById(R.id.txtEstado);
textPais = (TextView) findViewById(R.id.txtPais);
textRua = (TextView) findViewById(R.id.txtRua);
double latti = 0.0;
double longi = 0.0;
locationManager = (LocationManager) getSystemService(Context.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) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}else{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latti = location.getLatitude();
longi = location.getLongitude();
textLati.setText("Latitude: "+latti);
textLong.setText("Logitude: "+longi);
}
}
try{
endereco = buscaEndereco(latti, longi);
textCidade.setText("Cidade: "+ endereco.getLocality());
textEstado.setText("Estado: "+ endereco.getAdminArea());
textPais.setText("Pais: "+ endereco.getCountryName());
textRua.setText("" + endereco.getAddressLine(0));
}catch (IOException e){
e.printStackTrace();
}
}
public Address buscaEndereco(double latitude, double longitude)throws IOException{
Geocoder geocoder;
Address address = null;
List<Address> addresses;
geocoder = new Geocoder(getApplicationContext());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0 ){
address = addresses.get(0);
}
return address;
}
}