Helper class best approach android
Asked Answered
V

4

2

I was looking at Google I/O Android App iosched link and saw that they use mostly static methods in their helper/util classes. However, I have found many people not recommending the use of static methods in helper classes.

Let's say if I have 3 activities that are doing some work like showing alert dialog or notification, then I need to add the same code in all the 3 activities. What if I am writing in files from 10 different activities. Isn't using a helper class with a static method a better approach than writing same code again and again? if not then what is the best approach.

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);
  }
}
Vesicle answered 4/2, 2017 at 10:51 Comment(0)
S
7

Usuage of Helper classes is little debatable in object oriented programming. You can use normal class and include the object of the class. Or you may put common code in a base class and then extend it. But if we decide to use Helper classes then below are the few points which may help you as guideline.

  1. Helper classes are the utility entities. They are better used just like utility so prevent the instantiation and extension by marking the default constructor as private.

  2. Expose the ' static ' methods. See if the methods are just needed by the classes in the package as of the utility class, then keep the acess modifer as package-private, and if needed by classes outside also then you can make them public. The intent is to prevent exposing package details too much by public APIs. You can also try to have abstractions in parametrs and return type.

  3. Try to keep such classes as stateless by not having fields. Keeping the ( static ) fields may lead referencing objects even when not needed.

  4. Name such classes properly to let users of the helper class know its intention and also that they are just utility classes. Also name the methods according to use and to minimize the confusions.

Shanda answered 4/2, 2017 at 11:2 Comment(4)
I agree with all points apart from 2, generally I feel that the minimum scope should be kept, even for utility methods. I prefer to start with package-private, and only expose as public if necessary.Lipp
@Lipp Keen, yes agreed.. will add your point. I just wanted to say to expose static methods and while saying so went a step ahead and added public.Shanda
I have a database that reads and writes values from various places. Should I make its method static in a helper classVesicle
@MohakPuri If the methods do not use only the local variables and parameters, also if they do not call any instance method of the class then you may make them static methods.Shanda
A
2

Few points to remember related to use of Utility classes (some of them already touched upon the previous answer) -

  1. Generally if you have a couple of activities doing something common like using the same networking layer, showing general error prompts and notifications then the best approach is to put them in a BaseActivity and let all your activities extend them. If you may, use OOPS concepts like grouping behaviors into interfaces, defining abstract methods which child activities must extend and stuffs like that. Avoid doing anything specific in the BaseActivity and let the child activities take as much control as possible.

  2. If you have to have utility classes, make them singleton and without any state.

  3. Avoid doing async tasks in the utility methods. Remember each component on Android has a lifecycle and any async task you do must be tied to the lifecycle of the hosting component. So for e.g if you are doing a File operation which you think must take a while, then wrap it in a asynctask or something in your calling component.

  4. Utility classes are good members for injection (my opinion !!). Try using a DI library like Dagger to make your life easier if you end up using too many utility libraries.

Angkor answered 4/2, 2017 at 11:29 Comment(0)
K
1

Network Availability check in 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();
    }
}
Kassel answered 2/3, 2019 at 10:40 Comment(0)
K
0

Internet connectivity in Android, Code for Internet connection speed check, Internet Speed checking in android phone

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;
        }
    }

}
Kassel answered 2/3, 2019 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.