繁体   English   中英

助手类最佳方法android

[英]Helper class best approach android

我正在查看 Google I/O Android App iosched链接,发现他们在 helper/util 类中主要使用静态方法。 但是,我发现很多人不推荐在辅助类中使用静态方法。

假设我有 3 个活动正在执行一些工作,例如显示警报对话框或通知,那么我需要在所有 3 个活动中添加相同的代码。 如果我正在编写来自 10 个不同活动的文件怎么办。 使用带有静态方法的辅助类不是比一遍又一遍地编写相同的代码更好的方法吗? 如果不是,那么最好的方法是什么。

public class NotificationHelper {

  /**
   * create notification
   * @param context activity context
   * @param title notification title
   * @param contentText notification text
   * @param mNotificationId notification id
   */
  public static void setUpNotification(Context context, String title, String contentText, int mNotificationId) {

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context).setLargeIcon((BitmapFactory.decodeResource(context.getResources(),R.drawable.launcher)))
                    .setSmallIcon(R.drawable.ic_notif)
                    .setContentTitle(title)
                    .setContentText(contentText).setPriority(NotificationCompat.PRIORITY_MAX);

    Intent resultIntent = new Intent(context, MainActivity.class);
    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    context,
                    0,
                    resultIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mBuilder.setOngoing(true);
    NotificationManager mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(mNotificationId, mBuilder.build());
}

  /**
   * cancel notification
   * @param ctx context
   * @param notifyId id of notification to be cancelled
   */
  public static void cancelNotification(Context ctx, int notifyId) {
    NotificationManager nMgr = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    nMgr.cancel(notifyId);
  }
}

Helper classes在面向对象编程中几乎没有争议。 您可以使用普通类并包含类的对象。 或者您可以将公共代码放在基类中,然后对其进行扩展。 但是,如果我们决定使用 Helper 类,那么以下几点可以帮助您作为指导。

  1. 助手类是实用程序实体。 它们最好像实用程序一样使用,因此通过将默认构造函数标记为私有来防止实例化和扩展。

  2. 公开“静态”方法。 看看这些方法是否只是作为实用程序类的包中的类需要,然后将访问修饰符保留为包私有,如果外部类也需要这些方法,那么您可以将它们设为公共。 目的是防止公共 API 过多地暴露包详细信息。 您还可以尝试在参数和返回类型中进行抽象。

  3. 尝试通过没有字段来使此类类保持为stateless 即使不需要,保持(静态)字段也可能导致引用对象。

  4. 正确命名这些类,让帮助类的用户知道它的意图,并且它们只是实用程序类。 还要根据用途命名方法并尽量减少混淆。

与实用程序类的使用相关的几点要记住(其中一些已经涉及到上一个答案)-

  1. 通常,如果您有几个活动在做一些常见的事情,例如使用相同的网络层,显示一般错误提示和通知,那么最好的方法是将它们放在BaseActivity并让您的所有活动扩展它们。 如果可以,请使用 OOPS 概念,例如将行为分组到接口中,定义子活动必须扩展的抽象方法等等。 避免在BaseActivity做任何特定的BaseActivity并让子活动尽可能多地控制。

  2. 如果您必须拥有实用程序类,请将它们设为单例且没有任何状态。

  3. 避免在实用程序方法中执行异步任务。 请记住,Android 上的每个组件都有一个生命周期,您执行的任何异步任务都必须与托管组件的生命周期相关联。 因此,例如,如果您正在执行一个您认为必须花费一段时间的文件操作,则将其包装在asynctask或调用组件中的其他内容中。

  4. 实用程序类是注入的好成员(我认为!!)。 如果您最终使用了太多实用程序库,请尝试使用像 Dagger 这样的 DI 库来让您的生活更轻松。

android中的网络可用性检查

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class NetworkUtil {
    public static boolean isNetworkAvailable(Context context)
    {
        ConnectivityManager connectivityManager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

互联网连接速度检查

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

/**
 * Check device's network connectivity and speed 
 * @author emil http://stackoverflow.com/users/220710/emil
 *
 */
public class Connectivity {

    /**
     * Get the network info
     * @param context
     * @return
     */
    public static NetworkInfo getNetworkInfo(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    /**
     * Check if there is any connectivity
     * @param context
     * @return
     */
    public static boolean isConnected(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected());
    }

    /**
     * Check if there is any connectivity to a Wifi network
     * @param context
     * @param type
     * @return
     */
    public static boolean isConnectedWifi(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
    }

    /**
     * Check if there is any connectivity to a mobile network
     * @param context
     * @param type
     * @return
     */
    public static boolean isConnectedMobile(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    /**
     * Check if there is fast connectivity
     * @param context
     * @return
     */
    public static boolean isConnectedFast(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(),info.getSubtype()));
    }

    /**
     * Check if the connection is fast
     * @param type
     * @param subType
     * @return
     */
    public static boolean isConnectionFast(int type, int subType){
        if(type==ConnectivityManager.TYPE_WIFI){
            return true;
        }else if(type==ConnectivityManager.TYPE_MOBILE){
            switch(subType){
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            /*
             * Above API level 7, make sure to set android:targetSdkVersion 
             * to appropriate level to use these
             */
            case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
                return false; // ~25 kbps 
            case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
                return true; // ~ 10+ Mbps
            // Unknown
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            default:
                return false;
            }
        }else{
            return false;
        }
    }

}

暂无
暂无

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

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