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);
}
}
package-private
, and only expose aspublic
if necessary. – Lipp