爲其餘對象提供一種代理以控制對這個對象的訪問設計模式
public abstract class Notify {
protected Context context;
protected NotificationManager notificationManager;
protected NotificationCompat.Builder builder;
public Notify(Context context) {
this.context = context;
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(PendingIntent.getActivity(context, 0,
new Intent(context, NotifyActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT));
}
/**
* 發送一條通知
*/
public abstract void send();
/**
* 取消一條通知
*/
public abstract void cancel();
}
複製代碼
public class NotifyNormal extends Notify {
public NotifyNormal(Context context) {
super(context);
}
@Override
public void send() {
builder.setContent(new RemoteViews(context.getPackageName(), R.layout.layout_notify_normal));
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
@Override
public void cancel() {
notificationManager.cancel(0);
}
}
複製代碼
public class NotifyBig extends Notify {
public NotifyBig (Context context) {
super(context);
}
@Override
public void send() {
builder.setContent(new RemoteViews(context.getPackageName(), R.layout.layout_notify_normal));
builder.setCustomBigContentView(new RemoteViews(context.getPackageName(), R.layout.layout_notify_normal));
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
@Override
public void cancel() {
notificationManager.cancel(0);
}
}
複製代碼
public class NotifyHeadersUp extends Notify {
public NotifyHeadersUp (Context context) {
super(context);
}
@Override
public void send() {
builder.setContent(new RemoteViews(context.getPackageName(), R.layout.layout_notify_normal));
builder.setCustomBigContentView(new RemoteViews(context.getPackageName(), R.layout.layout_notify_normal));
builder.setCustomHeadsUpContentView(new RemoteViews(context.getPackageName(), R.layout.layout_notify_normal));
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
@Override
public void cancel() {
notificationManager.cancel(0);
}
}
複製代碼
public class NotifyProxy extends Notify {
private Notify notify;
public NotifyProxy (Context context) {
super(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notify = new NotifyHeadersUp(context);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
notify = new NotifyBig(context);
} else {
notify = new NotifyNormal(context);
}
}
@Override
public void send() {
notify.send();
}
@Override
public void cancel() {
notify.cancel();
}
}
複製代碼
new NotifyProxy(MainActivity.this).send();
複製代碼
歡迎關注個人微信公衆號,期待與你一塊兒學習,一塊兒交流,一塊兒成長! bash