1.通知的使用場合
當(dāng)某個(gè)應(yīng)用程序希望向用戶發(fā)出一些提示信息,而該應(yīng)用程序又不在前臺運(yùn)行時(shí),就可以借助通知來實(shí)現(xiàn)。發(fā)出一條通知后,手機(jī)最上方的狀態(tài)欄中會顯示一個(gè)通知的圖標(biāo),下拉狀態(tài)欄后可以看到通知的詳細(xì)內(nèi)容。
2.通知的創(chuàng)建步驟
(1)獲取NotificationManager實(shí)例,可以通過調(diào)用Conten的getSystenService()方法得到,getSystemService()方法接收一個(gè)字符串參數(shù)用于確定獲取系統(tǒng)的哪個(gè)服務(wù),這里我們傳入Context.NOTIFICATION_SERVICE即可。獲取NotificationManager實(shí)例如下:
NotificationManager manager =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
(2)創(chuàng)建Notification對象,該對象用于存儲通知的各種所需信息,我們可以使用它的有參構(gòu)造函數(shù)來創(chuàng)建。構(gòu)造函數(shù)有三個(gè)參數(shù),第一個(gè)參數(shù)指定通知圖標(biāo),第二個(gè)參數(shù)用于指定通知的ticker內(nèi)容,當(dāng)通知剛被創(chuàng)建的時(shí)候,它會在系統(tǒng)的狀態(tài)欄一閃而過,屬于一種瞬時(shí)的提示信息。第三個(gè)參數(shù)用于指定通知被創(chuàng)建的時(shí)間,以毫秒為單位,當(dāng)下拉系統(tǒng)狀態(tài)欄時(shí),這里指定的時(shí)間會顯示在相應(yīng)的通知上。創(chuàng)建一個(gè)Notification對象可以寫成:
Notification notification = new
Notification(R.drawable.ic_launcher,"This is a ticker
text",System.currentTimeMillis());
(3)調(diào)用Notification的setLatestEventIfo()方法對通知的布局進(jìn)行設(shè)定,這個(gè)方法接收四個(gè)參數(shù),第一個(gè)參數(shù)是Context。第二個(gè)參數(shù)用于指定通知的標(biāo)題內(nèi)容,下拉系統(tǒng)狀態(tài)欄就可以看到這部分內(nèi)容。第三個(gè)參數(shù)用于指定通知的正文內(nèi)容,同樣下拉系統(tǒng)狀態(tài)欄就可以看到這部分內(nèi)容。第四個(gè)參數(shù)用于指定實(shí)現(xiàn)通知點(diǎn)擊事件的PendingIntent對象,如果暫時(shí)用不到可以先傳入null。因此,對通知的布局進(jìn)行設(shè)定就可以寫成:
notification.setLatestEventInfo(context,
"This is content title", "This iscontent text", null);
(4)調(diào)用NotificationManager的notify()方法顯示通知。notify()方法接收兩個(gè)參數(shù),第一個(gè)參數(shù)是id,要保證為每個(gè)通知所指定的id都是不同的。第二個(gè)參數(shù)則是Notification對象,這里直接將我們剛剛創(chuàng)建好的Notification對象傳入即可。顯示一個(gè)通知就可以寫成:
manager.notify(1,
notification);
3.代碼示例
public class MainActivity extends Activity implements OnClickListener {
private Button sendNotice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendNotice = (Button) findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.send_notice:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(
R.drawable.ic_launcher, "This is a ticker text", System.currentTimeMillis());
notification.setLatestEventInfo(this, "This is content title",
"This is content text", null);
manager.notify(1, notification);
default:
break;
}
}
}
另外,我在開發(fā)完APP都會用一些APP在線自動化測試工具進(jìn)行測試:www.ineice.com