为其余对象提供一种代理以控制对这个对象的访问设计模式
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