1. 通知的使用場合
當某個應用程序希望向用戶發出一些提示信息,而該應用程序又不在前台運行時,就可以借助通知來實現。發出一條通知后,手機最上方的狀態欄中會顯示一個通知的圖標,下拉狀態欄后可以看到通知的詳細內容。
2. 通知的創建步驟
(1)獲取NotificationManager實例,可以通過調用Conten的getSystenService()方法得到,getSystemService()方法接收一個字符串參數用於確定獲取系統的哪個服務, 這里我們傳入Context.NOTIFICATION_SERVICE 即可。獲取NotificationManager實例如下:
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
(2)創建Notification對象,該對象用於存儲通知的各種所需信息,我們可以使用它的有參構造函數來創建。構造函數有三個參數,第一個參數指定通知圖標,第二個參數用於指定通知的ticker 內容,當通知剛被創建的時候,它會在系統的狀態欄一閃而過,屬於一種瞬時的提示信息。第三個參數用於指定通知被創建的時間,以毫秒為單位,當下拉系統狀態欄時,這里指定的時間會顯示在相應的通知上。創建一個Notification 對象可以寫成:
Notification notification = new Notification(R.drawable.ic_launcher,"This is a ticker text",System.currentTimeMillis());
(3)調用Notification的setLatestEventIfo()方法對通知的布局進行設定,這個方法接收四個參數,第一個參數是Context。第二個參數用於指定通知的標題內容,下拉系統狀態欄就可以看到這部分內容。第三個參數用於指定通知的正文內容,同樣下拉系統狀態欄就可以看到這部分內容。第四個參數用於指定實現通知點擊事件的PendingIntent對象,如果暫時用不到可以先傳入null。因此,對通知的布局進行設定就可以寫成:
notification.setLatestEventInfo(context, "This is content title", "This iscontent text", null);
(4)調用NotificationManager的notify()方法顯示通知。notify()方法接收兩個參數,第一個參數是id,要保證為每個通知所指定的id 都是不同的。第二個參數則是Notification 對象,這里直接將我們剛剛創建好的Notification 對象傳入即可。顯示一個通知就可以寫成:
manager.notify(1, notification);
3.代碼示例

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/send_notice" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Send notice" /> </LinearLayout>
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; } } }