編輯:關於 Android 程式設計
通知是應用與使用者溝通的重要橋樑。建立一則通知,大致包含四個環節:建立通知的 Builder、定義通知的行為、設定點擊事件,以及發出通知。以下逐一拆解。
補充:使用 NotificationCompat.Builder 需引入 support 套件。延伸閱讀可參考官方文件 Notifications API Guide、Intents and Intent Filters 以及 Notifications Design Guide。
建立 Notification 時,NotificationCompat.Builder 負責定義其 UI。Builder 至少應包含以下方法:
setSmallIcon() 設定圖示 setContentTitle() 設定標題 setContentText() 設定詳情文字
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
雖然 action 是可選的,但仍強烈建議為通知加上一個。它能讓使用者直接從通知欄跳轉到你的 Activity,查看觸發通知的事件並做相應操作。在通知內部,action 是透過一個含 Intent 的 PendingIntent 來啟動 Activity。
Intent resultIntent = new Intent(this, ResultActivity.class);
// 由於點擊通知會開啟一個全新的 Activity,
// 因此無需建立人為的回退堆疊
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
以先前建立的 PendingIntent 關聯到手勢上,呼叫 Builder 的對應方法即可。例如以 setContentIntent() 加入 PendingIntent,讓使用者點擊時啟動某個 Activity:
mBuilder.setContentIntent(resultPendingIntent);
發出通知需满足兩個條件:取得 NotificationManager 的實例,並使用 notify() 方法發出。呼叫 notify() 時需帶上一個特定的 id,日後可透過這個 id 來更新通知;最後呼叫 build() 取得包含說明的 Notification 物件。
int mNotificationId = 001; NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotifyMgr.notify(mNotificationId, mBuilder.build());
完整程式碼如下:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, AActicity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = 001;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
// notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; // 可使通知常駐通知欄
mNotifyMgr.notify(mNotificationId, notification);
若想讓通知常駐通知欄不被清除,可加上 FLAG_ONGOING_EVENT 與 FLAG_NO_CLEAR 旗標。掌握這套流程,你就能輕鬆地在應用中送出功能完整的通知。
Android 屏幕適配五種方案詳解:從像素密度到權重布局
什麼是屏幕適配 所謂適配,就是讓同一個應用在不同的手機上呈現一致的視覺效果。動手之前,第一步永遠是先確認當前設備屬於哪一檔像素密度(xhdpi、hdpi、mdpi 等)。
Android ListView 下拉到底自動加載更多功能的實現解析
透過動手實作這個小範例,可以收穫不少實用的知識點:如何為 ListView 加入分頁加載、如何自訂控制項、如何優化 ListView 的滾動效能、如何靈活使用 BaseA
Android 區域填色實作:分層著色與掃描線填充演算法解析
在著色遊戲或簡易繪圖應用中,使用者點擊畫面某個區域後,該區域立即變色,是很常見的互動效果。要實作這個功能,可以從兩種思路切入:分層圖像填色與邊界演算法填色。 分層填色:以
從需求到上線:天氣預報 App 開發流程完整解析
許多新手在拿到需求後,常會卡在「不知道從哪裡開始」。本文以一個簡單的天氣預報 App 為例,說明從需求梳理、原型設計、架構選擇到開發上線的完整思路。 宏觀流程:一個專案如