简体   繁体   English

Android:几个共享公共代码的活动

[英]Android : Several activities sharing common code

I have an Android application composed by several Activities. 我有一个由几个活动组成的Android应用程序。 Most of them need to check whether an active network is available or not: 他们中的大多数人需要检查活动网络是否可用:

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    ...
}

I would like to move that code to a helper class in order to avoid the need to write that code in every Activity, but calls to getSystemService are only allowed from an Activity. 我想将该代码移动到辅助类,以避免在每个Activity中编写该代码,但只允许从Activity调用getSystemService

The other alternative is to move that code to a parent activity use inheritance but: 另一种方法是将该代码移动到父活动使用继承,但是:

  1. Every activity already extends from android.app.Activity 每个活动都已经从android.app.Activity扩展
  2. Some of my activities already extend from a common my.package.BaseActivity (Activity <- BaseActivity <- XXXActivity) 我的一些活动已经从常见的my.package.BaseActivity扩展(Activity < - BaseActivity < - XXXActivity)

so I don't like this idea very much. 所以我不太喜欢这个想法。

What do you recommend in this case? 在这种情况下你会推荐什么? Is there any other alternative? 还有其他选择吗?

Well, you could still create a helper class and pass a reference of the activity to it. 好吧,您仍然可以创建一个辅助类并将活动的引用传递给它。

public boolean isNetworkAvailable(Context c) {
    ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
    ...
}

getSystemService is a public method, so it should work outside of the Activity scope. getSystemService是一个公共方法,因此它应该在Activity范围之外工作。

You could pass it by calling it like this: 您可以通过这样调用它来传递它:

helperClassObj.isNetworkAvailable(YourActivity.this);

Hope this works for you. 希望这对你有用。

Can't you just use composition? 你不能只使用作文吗? Define a class with your logic and then put that class or an instance of it into the classes that need the method. 使用您的逻辑定义一个类,然后将该类或其实例放入需要该方法的类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM