java - Android中如何避免跨类重复代码?

标签 java android constructor

我需要在应用程序的不同屏幕中检索用户位置。我已经编写了代码来获取一个屏幕 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/

相关文章:

java - 模数运算返回奇怪的结果

带或不带 new 运算符的 JavaScript 构造函数

javax.命名.NameNotFoundException : jms

java - 使用条件转换 HashMap 中的 Stream

java - 将 node.js 进程与 java/scala 代码连接起来的最快方法

java - 在哪些架构/操作系统中,其他线程可以在构造函数调用后看到默认的非最终字段值?

c++ - 构造函数中的临时非常量 istream 引用 (C++)

java - Android海量数据库创建

android - 使用简单的光标拖放

android - 如何预加载 Activity ?