編輯:關於 Android 開發
通知欄是 Android 應用與使用者互動的重要管道。本文說明如何使用 NotificationManager 與 Notification 兩個類別,在系統通知欄中送出通知。
背景知識:通知可由 Activity 或 Service 觸發,兩者的差別在於一個於前台觸發,一個於後台服務觸發。NotificationManager 透過 getSystemService 取得,並以 notify 方法向系統發送通知。
// 取得 NotificationManager String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); // 通知欄狀態列顯示的內容 int icon = R.drawable.icon; CharSequence tickerText = "我的通知欄標題"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); // 下拉通知欄時展開顯示的內容 Context context = getApplicationContext(); CharSequence contentTitle = "我的通知欄展開標題"; CharSequence contentText = "我的通知欄展開詳細內容"; Intent notificationIntent = new Intent(this, BootStartDemo.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); // 發送通知 mNotificationManager.notify(1, notification);
重點在於:以 Notification 描述狀態列的圖示與提示文字,再以 PendingIntent 封裝點擊通知後要啟動的 Intent,最後呼叫 notify(id, notification) 送出。每則通知都有一個唯一 id,可用於後續更新或移除對應通知。
行動應用支付系列(一):手把手集成支付寶支付
行動應用支付系列(一):手把手集成支付寶支付 在行動應用百花齊放的時代,隨著行動支付的盛行,越來越多的 App 都集成了支付功能。以往支付從不是我負責的模塊,近期專案由我
Android 自定義 View 與自定義屬性實戰:打造安全衛士設置中心
Android 自定義 View 與自定義屬性實戰:打造安全衛士設置中心 本篇以「手機安全衛士」的設置中心為例,示範如何封裝可重複使用的自定義組合控件,並透過自定義屬性簡
深入解析 ListView 聯動:仿餓了麼點餐界面
透視雙 ListView 聯動的實現原理 本文將對「仿餓了麼點餐界面」中兩個 ListView 聯動的效果進行代碼層面的深入剖析。通過拆解大神的經典實現,既能方便自己日後
Android 動態部署(五):如何從插件 APK 中啟動 Service
Android 動態部署(五):如何從插件 APK 中啟動 Service 經過前幾篇的分析,我們了解到 Google 原生是如何拆分 APK 的,並且可以自己透過解析