安開發卓之Notification(一)代碼直接能用,安開發notification

來源:互聯網
上載者:User

安開發卓之Notification(一)代碼直接能用,安開發notification

  Notification是Android中很理想的一種顯示提示資訊的方法,它可以將應用程式的資訊傳遞到我們的Android案頭狀態列,採用這種訊息傳遞方式不會影響到使用者對手機的正常使用。而且Notification不僅僅可以傳遞文字資訊,還可以傳遞圖片資訊,甚至可以將我們的控制項追加到上面,只要使用者不對其進行清空,那麼訊息將一直儲存在使用者案頭的狀態列當中。

Notification通常用來進行對使用者的更新提醒等訊息的傳遞。

  Notification需要使用到NotificationManager(訊息通知管理類)對訊息進行管理,其建立需要五個步驟:

(1)通過getSystemService擷取Notification對象

(2)建立一個Notification,每一個notification對應一個notification對象。

(3)建立一個PendingIntent對象

(4)使用notification類的setLatestEventInfo方法設定Notification對象的詳細資料

(5)使用NotificationManager對象的notify方法顯示訊息

 

在第二步時應當注意需要設定顯示在螢幕上方狀態列的通知訊息、通知訊息前方的映像資源ID和放出通知的時間,一般為目前時間

(3)建立PendingIntent對象:

由於notification可以與應用程式脫離,也就是說你的應用程式已經關閉,訊息仍然顯示在狀態列之中,當應用程式再次啟動後,又可以重新控制這些notification,如清除、替換等工作。因此需要PendingIntent對象,該對象由安卓系統維護,因此,應用程式關閉後,訊息仍然不會被釋放。

(4)在使用notify方法時需要指定Notification對象的唯一ID,這個ID必須相對於一個Notificationmanager對象來說是唯一的,否則就會覆蓋相同ID的

Notification

NotificationManager manager  = (NotificationManager)

    getSystemService(NOTIFICATION_SERVICE);

    String notice = "您有短訊息了!";

    Notification notification = new Notification(R.drawable.ic_launcher, notice,System.currentTimeMillis());

    PendingIntent contentIntent = PendingIntent.getActivity

    (getApplicationContext(), 0, getIntent(), 0);

    notification.setLatestEventInfo

    (getApplicationContext(), "小搬運工又變帥了", "華中軟體龍頭企業", contentIntent);

    notification.defaults = Notification.DEFAULT_SOUND;

    notification.defaults = Notification.DEFAULT_LIGHTS;

    notification.defaults = Notification.DEFAULT_VIBRATE;

    notification.defaults = Notification.DEFAULT_ALL;

    manager.notify(R.drawable.ic_launcher,notification);

1、如果要調取聲音,需用使用到:android:name=“android.permission.VIBRATE”許可權

  NotificationManager.cancel(resId)清除某個資料 NotificationManager.cancelAll()清除某個NotificationManager對象中的所有訊息。
在清除完訊息後,需要做一些善後工作,需要通過notification,deleteIntent來完成,deleteIntent也需要一個pendingIntent類型的變數,用於在清除所用的notification對象時調用。這個動作可以與Activity、Service、Broadcast關聯。

如果想永久儲存推送的通知,需要增加代碼:

•notification.flags = Notification.FLAG_NO_CLEAR;

 

聯繫我們

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