編寫Android通知示例
這樣的場景:OA中的報銷審批。如果老闆公務纏身,經常出差,員工經常會抱怨得不到及時的報銷審批。因此類似審批性質的需求在移動OA中很常用。
下面用這樣的場景演示一下Android的通知的使用。
寫了個簡單的Activity,按按鈕,就產生一個通知,並且有聲音提示。
下拉通知欄:
點選該通知條目,重新進入上面的那個簡單的Activity,當然可以打開其他的Activity,這裏爲了示例簡單。
可以看到這回提示的通知圖標在點選後消失了。
源代碼見:
http://easymorse.googlecode.com/svn/trunk/android.notification/
主要起作用的代碼,就是點擊按鈕後的處理部分:
button.setOnClickListener(newOnClickListener() {
@Override
public void onClick(View v) {
NotificationManager manager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = newNotification(R.drawable.icon,
"收到公文",System.currentTimeMillis());
notification.setLatestEventInfo(getApplicationContext(),"張三-報銷審批",
"張三-差旅費-上海世博會-3646元",
PendingIntent.getActivity(
LaunchNotificationActivity.this, 0,
new Intent(LaunchNotificationActivity.this,LaunchNotificationActivity.class),0));
notification.flags|=Notification.FLAG_AUTO_CANCEL;
notification.defaults |=Notification.DEFAULT_SOUND;
manager.notify(1, notification);
}
});
這裏一上來要得到NotificationManager,這是系統服務,已經存在,可以通過getSystemService()方法得到。
創建Notification的時候需要一些參數,一個圖標,一個用於提示的文字,還有通知的時間:
Notificationnotification = new Notification(R.drawable.icon,
"收到公文",System.currentTimeMillis());
還要設置下拉通知欄的一些內容:題目,文字,點擊該通知條目的動作。在本例中是點擊後跳到一個Activity上:
notification.setLatestEventInfo(getApplicationContext(),"張三-報銷審批",
"張三-差旅費-上海世博會-3646元",
PendingIntent.getActivity(
LaunchNotificationActivity.this, 0,
new Intent(LaunchNotificationActivity.this,LaunchNotificationActivity.class),0));
再往後,設置了一個點選後不再在通知欄中顯示:
notification.flags|=Notification.FLAG_AUTO_CANCEL;
設置聲音:
notification.defaults|= Notification.DEFAULT_SOUND;
再把通知加到NotifacationManager中:
manager.notify(1,notification);
這裏的數字,是個id,這裏是常數1,如果多次點擊收到公文按鈕,不會出現多個通知。如果每次加1,則可生成多個通知。