跟我學android-Notification,android

來源:互聯網
上載者:User

跟我學android-Notification,android

Notification 可以理解為通知的意思,會出現在通知欄,比如來了一條簡訊

使用 Notification 有以下3個步驟:

1. 建立 NotificationManager的對象

2.為Notification設定屬性

3.使用 NotificationManager 提供的 notify 發送通知

 

執行個體:發出一個通知

 1     /** 2      * 建立notify 3      */ 4     private void createNotify() { 5         // 建立NotificationManager 對象 6         NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 7         // 建立notifyCation對象 8         Notification notify = new Notification(); 9         notify.icon = R.drawable.icon_reply;//設定表徵圖10         notify.when = System.currentTimeMillis();//發通知的時間,立即11         notify.tickerText = "hi,我來了";//提示文字12         notify.flags = Notification.FLAG_AUTO_CANCEL;//使用者點擊後 自動取消13         Intent intent = new Intent(this, NextActivity.class);14         PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,15                 PendingIntent.FLAG_UPDATE_CURRENT);16         notify.setLatestEventInfo(this, "來訊息啦", "一條通知", pIntent);17         manager.notify(10, notify);//發出通知,10是 通知的id18     }

這個方法 大家可以設定是 按鈕的事件裡 調用,運行程式後,點擊按鈕 就可以看到通知發送出來了。 布局檔案 和相關的代碼 這裡就不在編寫。

 

PendingIntent 為Intent的封裝,這裡是啟動Intent的描述,PendingIntent.getActivity 返回的PendingIntent表示

此PendingIntent執行個體中的Intent是用於啟動 Activity 的Intent。

PendingIntent.getActivity的參數依次為:Context,寄件者的請求碼(可以填0),用於系統發送的Intent,標誌位。

其中 PendingIntent.FLAG_UPDATE_CURRENT  表示如果該描述的PendingIntent已存在,則改變已存在的PendingIntent的Extra資料為新的PendingIntent的Extra資料。

 Intent 與 PendingIntent 的區別:

Intent :意圖,即告訴系統我要幹什麼,然後系統根據這個Intent做對應的事。如startActivity相當於發送訊息,而Intent是訊息的內容。

PendingIntent :封裝Intent,Intent 是我們直接使用 startActivity , startService 或 sendBroadcast 啟動某項工作的意圖。

而某些時候,我們並不能直接調用startActivity , startServide 或 sendBroadcast ,而是當程式或系統達到某一條件才發送Intent。

如這裡的Notification,當使用者點擊Notification之後,由系統發出一條Activity 的 Intent 。因此如果我們不用某種方法來告訴系統的話,系統是不知道是使用 startActivity ,

startService 還是 sendBroadcast 來啟動Intent 的(當然還有其他的“描述”),因此這裡便需要PendingIntent。

 


android中Notification設定的問題

你前面
notification.defaults=Notification.DEFAULT_LIGHTS;
後面又
notification.defaults=Notification.DEFAULT_VIBRATE;
所以DEFAULT_LIGHTS不起作用。

手機的鈴聲模式是鈴聲+無震動,應該調成鈴聲+震動模式。
 
Android:Notification的when是幹什用的?實驗後也沒發現

System.currentTimeMillis();
擷取當前的毫秒數
可以用來測試程式的已耗用時間

讀取資料的時候來計算時間的!
通知欄 設定 提示的間隔時間 ==s

通知欄的三個參數中,表徵圖內容,和發生時間。
Notification(icon, tickerText,when);
如果同一個通知欄有新的內容要更新根據這個時間來判斷更新。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.