我需要在应用程序的不同屏幕中检索用户位置。我已经编写了代码来获取一个屏幕 Activity 中的位置,但是,现在我也想获取另一个屏幕 Activity 中的位置。我可以做些什么来避免再次编写相同的代码吗?
// variables
// These variables will be repeated
LocationProvider locationProvider;
double latitude;
double longitude;
private String userPostcode;
// ===============
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// This code will be repeated
locationProvider = new LocationProvider(getActivity());
latitude = locationProvider.getLatitude();
longitude = locationProvider.getLongitude();
if (isNetworkAvailable(getContext())) {
getPostcode();
} else {
Toast.makeText(getActivity(), "Internet or GPS is not available. To get the best location one or both of these must be on",
Toast.LENGTH_LONG).show();
}
// =============
return inflater.inflate(R.layout.fragment_location, container, false);
}
// These two methods will be repeated
private void getPostcode(){
Geocoder geoCoder = new Geocoder(getActivity().getApplicationContext(), Locale.getDefault());
List<Address> address = null;
if (geoCoder != null) {
try {
address = geoCoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
if (address.size() > 0) {
userPostcode = address.get(0).getPostalCode();
}
}
}
private boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
// ====================
如果可以避免重复,请有人告诉我/告诉我如何做到这一点。我是 Android 新手,可能错过了一些愚蠢的事情。
最佳答案
在单独的类中添加 getPostcode()。您可以按如下方式修改。
public class Utils {
public static String getPostcode(Context context, double lat, double lng){
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<Address> address = null;
if (geoCoder != null) {
try {
address = geoCoder.getFromLocation(lat, lng, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
if (address.size() > 0) {
return address.get(0).getPostalCode();
}
}
return null;
}
public static boolean isNetworkAvailable(final Context context) {
final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
}
在您的 fragment/Activity 中执行此操作
if(Utils.isNetworkAvailable(this)) {
String postCode = Utils.getPostcode(this, yourLat, yourLng);
}
如果在 Fragment 中,请将 this
更改为 getActivity()
。
关于java - Android中如何避免跨类重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41609693/