- 獲取通知管理器
- 延遲執行的Intent
- 創建notification對象
- 實例化通知欄構造器創建佈局
- 顯示
獲取通知管理器
//獲取通知管理器
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
延遲執行的Intent
//延遲執行的Intent
Intent intent = new Intent(context, DisplayActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
實例化通知欄構造器創建佈局
//實例化通知欄構造器創建佈局
Notification notification = new Notification.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("通知啦")
.setContentText("通知通知通知通知通知通知通知通知通知通知")
.setContentIntent(pendingIntent)
.build();
顯示
//顯示
notificationManager.notify(0, notification);
取消
在跳到指定頁面或者完成指定操作後取消
NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
其他設置
播放音頻
//Uri soundUri=Uri.fromFile(new File(""));手機文件
//手機設置的默認提示音
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.setSound(soundUri)//聲音
設置振動
//數組下標爲0的值標識手機靜止的時長,下標爲1的值代表手機振動的時長,下標爲2的值又表示手機靜止的時長
//這句代碼意思是:立刻振動1秒,然後靜止1秒,再振動1秒
long[] vibrate = {0, 1000, 1000, 1000};
notification.setVibrate(vibrate)//振動
閃爍燈
notification.setLights(Color.GREEN, 1000, 1000)//設置閃爍燈