私はGoogle I/O Android Appを見ていました。linkがありました。ヘルパー/ユーティリティのクラスで静的メソッドがほとんど使用されていました。しかし、私は多くの人がヘルパークラスで静的メソッドの使用を推奨していないことを知っています。ヘルパークラスのベストアプローチアンドロイド
警告ダイアログや通知を表示するような作業を行っている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);
}
}
私は2から離れてすべての点に同意しますが、一般的には、実用的な方法であっても、最小限の範囲を維持する必要があります。私は 'package-private'で始まり、必要に応じて' public'として公開する方が好きです。 –
@マーク・キーン、はい合意しました。あなたの意見を追加します。私はちょうど静的メソッドを公開すると言っていたと言いながら、これを先に進んで公開しました。 –
私はさまざまな場所から値を読み書きするデータベースを持っています。そのメソッドをヘルパークラスで静的にする必要がありますか? –