通知(Notification)是Android系統(tǒng)中比較有特色的一個(gè)功能
創(chuàng)建一個(gè)通知的步驟
- 獲取通知的管理對(duì)象
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- 創(chuàng)建一個(gè)Notification對(duì)象枕扫,這個(gè)對(duì)象用于存儲(chǔ)通知所需的各種信息
/*
* 第一參數(shù):指定通知的圖標(biāo)
* 第二個(gè)參數(shù):指定通知的ticker內(nèi)容卦睹,當(dāng)通知被創(chuàng)創(chuàng)建的時(shí)候秽荞,它會(huì)在系統(tǒng)的系統(tǒng)欄一閃而過奸忽,屬于一種瞬時(shí)的提示消息
* 第三個(gè)參數(shù):指定通知被創(chuàng)建的時(shí)間幼东,以毫秒為單位
*/
Notification notification = new Notification(R.drawable.ic_launcher, "This is ticker Text", System.currentTimeMillis());
- 對(duì)通知的布局進(jìn)行設(shè)定
調(diào)用Notification
的setLatestEventInfo()
方法給通知設(shè)置一個(gè)標(biāo)準(zhǔn)布局
/*
* 第一個(gè)參數(shù):Context
* 第二個(gè)參數(shù):指定通知的標(biāo)題內(nèi)容
* 第三個(gè)參數(shù):指定通知的正文內(nèi)容
* 第四個(gè)參數(shù):PendingIntent意圖對(duì)象
*/
notification.setLatestEventInfo(this, "This is content Title", "This is content Text", pendingIntent);
- 顯示通知
調(diào)用NotificationManager
的notify()
方法可以讓通知顯示出來
/*
* 第一個(gè)參數(shù):為每個(gè)通知指定ID
* 第二個(gè)參數(shù):Notification對(duì)象
*/
manager.notify(1, notification);
- 通知消失
調(diào)用NotificationManager
的cancel()
方法就可以取消通知了
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//傳入的參數(shù)是Notification的ID
manager.cancel(1);
創(chuàng)建PendingIntent對(duì)象
PendingIntent也是一個(gè)'意圖'對(duì)象颊糜,Intent更傾向于立即執(zhí)行某個(gè)動(dòng)作凑阶,PendingIntent更傾向于在某個(gè)合適的時(shí)機(jī)去執(zhí)行某個(gè)動(dòng)作
獲取PendingIntent
對(duì)象相當(dāng)簡單瓦胎,PendingIntent
有一系列靜態(tài)方法可以獲取到該類的實(shí)例
-
getActivity()
方法 -
getBroadcast()
方法 -
getService()
方法
//創(chuàng)建一個(gè)意圖對(duì)象
Intent intent = new Intent(this, NotificationActivity.class);
/*
* 第一個(gè)參數(shù):Context對(duì)象
* 第二個(gè)參數(shù):一般用不到芬萍,傳入0即可
* 第三個(gè)參數(shù):一個(gè)Intent對(duì)象,通過這個(gè)對(duì)象可以構(gòu)建出PendingIntent的'意圖'
* 第四個(gè)參數(shù):確定PendingIntent的行為
*/
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
通知時(shí)的一些小效果
-
通知發(fā)出的時(shí)候搔啊,發(fā)出一段音頻
sound
屬性是notification
對(duì)外暴露的一個(gè)屬性柬祠,這是一個(gè)Uri對(duì)象
Uri soundUri = Uri.fromFile(new File("<path>"));
notification.sound = soundUri;
-
通知發(fā)出時(shí),手機(jī)振動(dòng)
使用的是vibrate
屬性负芋,它是一個(gè)長整型數(shù)據(jù)漫蛔,用于設(shè)置手機(jī)靜止和振動(dòng)的時(shí)長,以毫秒為單位。下標(biāo)為0的值表示手機(jī)靜止的時(shí)長惩猫,下標(biāo)為1的值表示手機(jī)振動(dòng)的時(shí)長芝硬,下標(biāo)為2的又表示手機(jī)靜止的時(shí)長,依次類推轧房。手機(jī)振動(dòng)需要聲明權(quán)限
通知來時(shí)拌阴,手機(jī)立刻振動(dòng)一秒,靜止一秒奶镶,再振動(dòng)一秒
long[] vibrates = {0, 1000, 1000, 1000};
notification.vibrate = vibrates;
- LED燈
//控制LED燈的顏色迟赃,三種顏色可選:紅、綠厂镇、藍(lán)
notification.ledARGB = Color.GREEN;
//指定LED燈亮起的時(shí)長纤壁,以毫秒為單位
notification.ledOnMS = 1000;
//指定LED燈暗去的時(shí)長,以毫秒為單位
notification.ledOffMS = 1000;
//flag指定通知的一些行為
notification.flags = Notification.FLAG_SHOW_LIGHTS;
不進(jìn)行個(gè)性化設(shè)置捺信,使用默認(rèn)通知提醒:
notification.defaults = Notification.DEFAULT_ALL;