// 創建通知 private void createNotification() { // 創建通知管理者 manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // 創建builder實例 builder = new Notification.Builder(MainActivity.this); // 設置小圖標 builder.setSmallIcon(R.mipmap.ic_launcher); // builder.setContentTitle(""); // builder.setContentText(""); // 點擊後不會自動消失 builder.setAutoCancel(false); // 不會滑動刪除通知 builder.setOngoing(false); // 設置優先級 builder.setPriority(Notification.PRIORITY_MAX); // 通知提示語 builder.setTicker("notification is build!"); // 提示音 震動 閃光 都爲系統默認 // builder.setDefaults(Notification.DEFAULT_ALL); builder.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.ring)); builder.setDefaults(Notification.DEFAULT_VIBRATE); // pendingIntent跳轉 Intent intent = new Intent(MainActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); notification = builder.build(); // 發起正在運行事件(活動中) // notification.flags = Notification.FLAG_ONGOING_EVENT; // 三色燈提醒 // notification.flags = Notification.FLAG_SHOW_LIGHTS; // 讓聲音、振動無限循環,直到用戶響應 (取消或者打開) notification.flags = Notification.FLAG_INSISTENT; // notification.flags = Notification.FLAG_ONLY_ALERT_ONCE ; // 只有全部清除時,Notification纔會清除 // notification.flags = Notification.FLAG_NO_CLEAR; // 自定義通知樣式 remoteView = new RemoteViews(getPackageName(), R.layout.layout_guard_notification); remoteView.setTextViewText(R.id.tv_notification_num, sdf.format(System.currentTimeMillis())); notification.contentView = remoteView; manager.notify(1990, notification); } 刷新通知:
remoteView.setTextViewText(R.id.tv_notification_num, sdf.format(System.currentTimeMillis())); manager.notify(1990, notification);取消通知:二選一
manager.cancel(1990);
manager.cancelAll();
DEMO鏈接