Android通知樣本(一)

來源:互聯網
上載者:User

這樣的情境:OA中的報銷審批。如果老闆公務纏身,經常出差,員工經常會抱怨得不到及時的報銷審批。因此類似審批性質的需求在移動OA中很常用。

下面用這樣的情境示範一下Android的通知的使用。

寫了個簡單的Activity,按按鈕,就產生一個通知,並且有聲音提示。

下拉通知欄:

 

點選該通知條目,重新進入上面的那個簡單的Activity,當然可以開啟其他的Activity,這裡為了樣本簡單。

可以看到這回提示的通知表徵圖在點選後消失了。

源碼見:

http://easymorse.googlecode.com/svn/trunk/android.notification/

主要起作用的代碼,就是點擊按鈕後的處理部分:

 1 button.setOnClickListener(new OnClickListener() { 
2 @Override
3 public void onClick(View v) {
4 NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
5 Notification notification = new Notification(R.drawable.icon,
6 "收到公文", System.currentTimeMillis());
7 notification.setLatestEventInfo(getApplicationContext(), "張三-報銷審批",
8 "張三-差旅費-上海世博會-3646元", PendingIntent.getActivity(
9 LaunchNotificationActivity.this, 0,
10 new Intent(LaunchNotificationActivity.this,LaunchNotificationActivity.class), 0));
11 notification.flags|=Notification.FLAG_AUTO_CANCEL;
12 notification.defaults |= Notification.DEFAULT_SOUND;
13 manager.notify(1, notification);
14 }
15 });

這裡一上來要得到NotificationManager,這是系統服務,已經存在,可以通過getSystemService()方法得到。

建立Notification的時候需要一些參數,一個表徵圖,一個用於提示的文字,還有通知的時間:

1 Notification notification = new Notification(R.drawable.icon, 
2 "收到公文", System.currentTimeMillis());

還要設定下拉通知欄的一些內容:題目,文字,點擊該通知條目的動作。在本例中是點擊後跳到一個Activity上:

1 notification.setLatestEventInfo(getApplicationContext(), "張三-報銷審批", 
2 "張三-差旅費-上海世博會-3646元", PendingIntent.getActivity(
3 LaunchNotificationActivity.this, 0,
4 new Intent(LaunchNotificationActivity.this,LaunchNotificationActivity.class), 0));
 1 再往後,設定了一個點選後不再在通知欄中顯示:
2
3 notification.flags|=Notification.FLAG_AUTO_CANCEL;
4
5 設定聲音:
6
7 notification.defaults |= Notification.DEFAULT_SOUND;
8
9 再把通知加到NotifacationManager中:
10
11 manager.notify(1, notification);
12
13 這裡的數字,是個id,這裡是常數1,如果多次點擊收到公文按鈕,不會出現多個通知。如果每次加1,則可產生多個通知。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.