我正在构建一个应用程序,我需要在其中获取设备位置和我使用的代码
Double latitude = 0.0;
Double longitude = 0.0;
String TAG = "HomeActivity";
Location gpsLoc = null, networkLoc = null, finallLoc = null;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Not Granted",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"Granted",Toast.LENGTH_LONG).show();
}
try{
gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}catch(Exception e){
e.printStackTrace();
}
if(gpsLoc!= null){
finallLoc = gpsLoc;
latitude = finallLoc.getLatitude();
longitude = finallLoc.getLongitude();
}else if(networkLoc!=null){
finallLoc = networkLoc;
latitude = finallLoc.getLatitude();
longitude = finallLoc.getLongitude();
}else{
latitude = 0.0;
longitude=0.0;
}
try{
Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1);
if(addresses!=null && addresses.size()>0){
String country = addresses.get(0).getCountryName();
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
}
}catch (Exception e){
e.printStackTrace();
}
我几乎准备好部署这个应用程序,我想确定我是否可以依靠这段代码来正确获取位置?如果没有,我应该做什么样的改进?代码工作正常只是想知道我是否缺少某些东西或在某些条件下可能导致错误的东西。