尝试使用以下方法获取位置。我已经在各种设备上测试了这种方法。
此代码适用于:华为P20PRO ,三星S6 edge plus ,小米redmi 5 。 它不适用于小米5,似乎代码无法获得他的位置。有人知道为什么吗?
public void getLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ZonaStudenti.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
}
else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);
/*location_func(location);*/
if (location != null) {
double latti = location.getLatitude();
double longi = location.getLongitude();
lattitude = String.valueOf(latti);
longitude = String.valueOf(longi);
latdaPass=latti;
longdaPass=longi;
try{
Geocoder geocoder=new Geocoder(this);
List<Address> adresses=null;
adresses=geocoder.getFromLocation(latti,longi,1);
String country=adresses.get(0).getCountryName();
String city=adresses.get(0).getLocality();
String Indirizzo = adresses.get(0).getAddressLine(0);
//citta.setText("Country: "+ country +"\n"+ "City: "+city);
//Toast.makeText(getApplicationContext(), "Country: "+ country +"\n"+ "City: "+city + "\n" + "Indirizzo: " + Indirizzo ,Toast.LENGTH_SHORT).show();
}catch (IOException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error" + e, Toast.LENGTH_SHORT).show();
}
}
else if (location1 != null)
{
double latti = location1.getLatitude();
double longi = location1.getLongitude();
lattitude = String.valueOf(latti);
longitude = String.valueOf(longi);
latdaPass=latti;
longdaPass=longi;
}
else if (location2 != null)
{
double latti = location2.getLatitude();
double longi = location2.getLongitude();
lattitude = String.valueOf(latti);
longitude = String.valueOf(longi);
latdaPass=latti;
longdaPass=longi;
}
else{
Toast.makeText(this,"Non trovo la posizione",Toast.LENGTH_SHORT).show();
}
}
}`