public class NotificationUtil {
private static final String TAG = AppConstants.APP_TAG + "NotificationUtil ";
private static volatile NotificationUtil mInstance;
private static Context mContext = MyApplication.getAppContext();
public NotificationUtil() {
}
/**
* get Instance.
*
* @return instance.
*/
public static NotificationUtil getInstance() {
if (mInstance == null) {
synchronized (NotificationUtil.class) {
if (mInstance == null) {
mInstance = new NotificationUtil();
}
}
}
return mInstance;
}
public void showNotification(int notificationId) {
LogUtil.d(TAG + "testNotification*");
RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.layout_surprise_notification);//自定义的布局视图
//RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.view_notification_layout);//自定义的布局视图
//按钮点击事件:
int requestCode = 1;
PendingIntent seeIntent = PendingIntent.getBroadcast(mContext, requestCode, new Intent(
AppConstants.NOTIFICATION_ACTION_SEE), PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent ignoreIntent = PendingIntent.getBroadcast(mContext, requestCode, new Intent(
AppConstants.NOTIFICATION_ACTION_IGNORE), PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.btn_see, seeIntent);//
views.setOnClickPendingIntent(R.id.btn_ignore, ignoreIntent);//
//创建通知:
String id = "channel_001";
String name = "name";
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
Notification notification = null;
notification = new Notification.Builder(mContext, id)
// .setChannelId(id)
// .setContentTitle("活动")
// .setContentText("您有一项新活动")
.setCustomBigContentView(views)
.setCustomContentView(views)
//.setContent(views)//设置布局
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher).build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(notificationId, notification);
}
}
notificationId每次调用会创建一个新的通知
在 requestcode 值一样的情况下 FLAG_UPDATE_CURRENT会更新之前PendingIntent的消息,FLAG_CANCEL_CURRENT 会取消之前的PendingIntent的消息
因此:只有 notificationId和requestcode每次都不同的情况下,才可以每次创建新的消息且可以接收对应的PendingIntent的消息