轉載請以連接形式標明出處: 本文出自:103style的博客bash
記錄一下app
NotificationManager.notify(int id, Notification notification)
發送到通知欄。id
.NotificationManager.cancel(id)
刪除對應的通知欄消息。經過sendNotification(...)
顯示推送消息,在對應的界面調用相似 cleanMsgNotify(int notice)
清除推送消息便可。ui
public static final String CHANNEL_ID = "XXXX";
private static NotificationManager mNotificationManager;
private static List<PushMessageBean> notifyList;
public synchronized static void cleanMsgNotify(int notice) {
if (mNotificationManager == null
|| notifyList == null || notifyList.size() == 0) {
return;
}
for (int i = notifyList.size() - 1; i >= 0; i--) {
PushMessageBean t = notifyList.get(i);
if (t.notice == notice) {
mNotificationManager.cancel(t.notifyId);
notifyList.remove(i);
}
}
}
public void sendNotification(Context context, PushMessageBean message) {
if (TextUtils.isEmpty(message.message)) {
return;
}
NotificationCompat.Builder mBuilder;
int notifyId = (int) System.currentTimeMillis();
if (mNotificationManager == null) {
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
registerNotificationChannel();
mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID);
mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setAutoCancel(true)
.setContentText(message.message)
.setSmallIcon(R.drawable.ic_launchers_round)
.setVibrate(new long[]{1000})
.setColor(context.getResources().getColor(R.color.color_primary))
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message.message));
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {//7.0以上不須要title
mBuilder.setContentTitle(context.getResources().getString(R.string.app_name));
}
message.notifyId = notifyId;
saveNotification(message);
mNotificationManager.notify(notifyId, mBuilder.build());
}
private void saveNotification(PushMessageBean message) {
if (notifyList == null) {
notifyList = new ArrayList<>();
}
notifyList.add(message);
}
private void registerNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = mNotificationManager.getNotificationChannel(CHANNEL_ID);
if (notificationChannel == null) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_ID, NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true); //是否在桌面icon右上角展現小紅點
channel.setLightColor(Color.RED); //小紅點顏色
//channel.setShowBadge(true); //是否在久按桌面圖標時顯示此渠道的通知
mNotificationManager.createNotificationChannel(channel);
}
}
}
複製代碼
若是以爲不錯的話,請幫忙點個讚唄。spa
以上code
掃描下面的二維碼,關注個人公衆號 Android1024, 點關注,不迷路。 cdn