編輯:Android 開發實例
前言
上一篇講了用 Toast 做輕量提示,本文來談論另一種更強大的消息推送方式——Notification。通知具備全局效果,通常由 NotificationManager 系統服務發送。本文會從基礎用法一路講到自定義樣式,並為每種形態配上示例代碼。
Notification 俗稱通知,它展示在螢幕頂端,先以一個圖標的形式停留在狀態列,用戶下拉時才展開具體內容。這種設計讓提示既不打斷當前操作,又不會被忽略。
兼容性提醒:Android 3.0 是 Notification API 的分水嶺。3.0 之前推薦使用 Notification.Builder 構建,3.0 之後則推薦 NotificationCompat.Builder——後者由支持庫提供,能讓同一套代碼在各版本上獲得一致且完整的表現。本文示例均在 4.3 環境下完成,若在 4.1 以下裝置測試,請留意差異。
發送通知需要兩樣東西:一個 Notification 對象承載內容,一個 NotificationManager 負責投遞。實務中很少直接 new Notification,而是通過 NotificationCompat.Builder 逐項設置屬性,最後調用 build() 產出對象,再交給 NotificationManager.notify() 發送。
NotificationManager 是系統級服務,以單例形式存在,不應自行實例化。在 Activity 中通過 getSystemService(String) 獲取,傳入 Context.NOTIFICATION_SERVICE 即可:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
雖然可設置的屬性很多,但有三項是必須的,缺一通知就無法正常展示:
setSmallIcon()setContentTitle()setContentText()NotificationManager.notify() 的第一個參數是通知標識符,用於唯一標識一條通知。這帶來了一個實用技巧:並非每次都要新建通知,很多場景下我們需要「刷新」同一條通知——比如下載進度。此時重新構建 Notification,並沿用相同的標識符再次 notify,新通知就會取代舊通知,達到原地更新的效果。
至於移除,Android 提供了兩種途徑:
setAutoCancel(true),用戶點擊後通知自動消失。cancel(int id) 移除指定通知,或 cancelAll() 清空全部。NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(0); // 移除 id 為 0 的通知
通知能承載的文字有限,通常只用來提示概要。用戶想了解詳情,就需要點擊通知跳轉到一個 Activity——這時要用到 PendingIntent,而不是普通的 Intent。
兩者的差別值得說清楚:Intent 處理「立刻發生」的意圖,PendingIntent 則是對 Intent 的包裝,處理「即將發生」的意圖。通知是系統級的全局對象,你的應用什麼時候被點擊、甚至是否還存活,都無法預知。PendingIntent 內部保存了觸發方的 Context,使得外部(系統)能夠以等同於你應用的身份去執行包裹的 Intent;即便發送通知的應用進程早已被回收,這份 Context 依然有效,Intent 附帶的 extras 也能正常傳遞。
PendingIntent 提供了多個靜態 getXxx() 方法以適配不同場景(getActivity、getService、getBroadcast 等)。參數大多直觀,唯獨 flag 值得單獨說明,它決定 PendingIntent 的構造策略:
FLAG_CANCEL_CURRENT:若已存在同類 PendingIntent,先取消舊的再新建。FLAG_NO_CREATE:若舊的不存在,則不新建,直接返回 null。FLAG_ONE_SHOT:該 PendingIntent 只能被使用一次。FLAG_UPDATE_CURRENT:若已存在則用新的 extras 更新它,日常最常用。通知有兩種視覺風格:標準視圖與大視圖(Big View)。標準視圖全版本通用,官方建議高度保持在 64dp,寬度鋪滿。它的內容區通常包含:
setWhen() 指定)btnNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap btm = BitmapFactory.decodeResource(getResources(), R.drawable.msg);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.msg)
.setContentTitle("5 new message")
.setContentText("someone@example.com")
.setLargeIcon(btm)
.setTicker("New message") // 首次提示時在狀態列滾動顯示
.setNumber(12) // 在圖標上疊加數字角標
.setAutoCancel(true); // 由通知自身維護消失
Intent resultIntent = new Intent(MainActivity.this, ResultActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
MainActivity.this, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
});
大視圖的詳情區最高可達 256dp,但僅 Android 4.1 及以上支持。它與標準視圖的差異全部通過 setStyle() 指定,傳入一個 NotificationCompat.Style 對象。這個抽象類提供了三個實現,分別適配不同場景:
BigPictureStyle:詳情區放一張大圖(上限 256dp 高),適合新聞配圖、聊天表情等。BigTextStyle:詳情區展示一大段富文本,適合長文推送。InboxStyle:詳情區展示多行清單式文本,適合郵件會話、多條消息摘要。btnBigViewNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bitmap btm = BitmapFactory.decodeResource(getResources(), R.drawable.msg);
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification noti = new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.msg)
.setLargeIcon(btm)
.setNumber(13)
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.InboxStyle()
.addLine("M.Twain (Google+) Haiku is more than a cert...")
.addLine("M.Twain Reminder")
.addLine("M.Twain Lunch?")
.addLine("M.Twain Revised Specs")
.addLine("Google Play Celebrate 25 billion apps with Goo..")
.addLine("Stack Exchange StackOverflow weekly Newsl...")
.setBigContentTitle("6 new message")
.setSummaryText("someone@example.com"))
.build();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, noti);
}
});
展開後可見多行摘要整齊排列,標題與歸屬信息獨立呈現在列表上方。
通知內容並非只能靜態展示。下載、上傳、同步這類耗時任務,可以在通知裡放一條進度條,讓用戶隨時掌握狀態。
關鍵方法是 setProgress(int max, int progress, boolean indeterminate):max 為總量,progress 為當前值,indeterminate 決定進度條形態——傳 false 是確定的刻度進度,傳 true 則是循環流動的不確定進度。
btnProgreNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Picture Download")
.setContentText("Download in progress");
builder.setAutoCancel(true);
// 通過子線程動態推進進度
new Thread(new Runnable() {
@Override
public void run() {
int incr;
for (incr = 0; incr <= 100; incr += 5) {
builder.setProgress(100, incr, false);
manager.notify(0, builder.build());
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Log.i(TAG, "sleep failure");
}
}
// 完成後清除進度條
builder.setContentText("Download complete")
.setProgress(0, 0, false);
manager.notify(0, builder.build());
}
}).start();
}
});
關鍵收尾細節:任務完成後調用 setProgress(0, 0, false) 再 notify 一次,進度條便會消失,通知回落到普通形態。
btnProNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Picture Download")
.setContentText("Download in progress");
builder.setProgress(0, 0, true); // true 表示循環流動
manager.notify(0, builder.build());
// 5 秒後停止流動
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
builder.setProgress(100, 100, false);
manager.notify(0, builder.build());
}
}).start();
}
});
和 Toast 一樣,通知也支持自定義樣式,但有一個關鍵差別:由於通知的全局性,觸發時你的應用可能已經被銷毀,無法正常 inflate 布局。因此不能像 Toast 那樣直接拿一個普通 View,而必須使用 RemoteViews。
RemoteViews 描述了一套可以跨進程顯示的視圖層次結構。它同樣是從布局文件「膨脹」而來,但只暴露了一組受限的操作方法,足夠在別的進程裡安全地更新界面。
構造方式一般為 RemoteViews(String packageName, int layoutId),第一個參數是包名,第二個是布局資源 ID。拿到實例後,用一系列 setXxx() 方法按控件 ID 設置屬性,最後交給 NotificationCompat.Builder.setContent(RemoteViews) 掛到通知上。
自定義布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<ImageView
android:id="@+id/imageNo"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_marginRight="10dp" />
<TextView
android:id="@+id/titleNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imageNo" />
<TextView
android:id="@+id/textNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/titleNo"
android:layout_toRightOf="@id/imageNo" />
</RelativeLayout>
實現代碼:
btnCustomNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RemoteViews contentViews = new RemoteViews(getPackageName(),
R.layout.custom_notification);
// 只能通過控件 ID 設置有限的屬性
contentViews.setImageViewResource(R.id.imageNo, R.drawable.btm1);
contentViews.setTextViewText(R.id.titleNo, "自定義通知標題");
contentViews.setTextViewText(R.id.textNo, "自定義通知內容");
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setTicker("new message")
.setContentIntent(pendingIntent)
.setContent(contentViews);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(10, mBuilder.build());
}
});
有些通知希望用戶立刻察覺,這時可以調用設備的鈴聲、指示燈與震動器。NotificationCompat.Builder 對應提供三個方法:
setSound(Uri sound):指定提示音,傳入形如 file:///mnt/sdcard/xxx.mp3 的 Uri。setLights(int argb, int onMs, int offMs):設置前置 LED 的顏色、亮起時長與熄滅時長(毫秒)。setVibrate(long[] pattern):以 long 數組描述震動節奏,元素為毫秒間隔,交錯表示震動與停頓。大多數時候並不需要定制獨特的提醒效果,遵循系統設置更妥當。此時用 setDefaults(int) 指定默認行為即可,常量已經備好:
DEFAULT_ALL:鈴聲、閃光、震動全部走系統默認。DEFAULT_SOUND:僅鈴聲默認。DEFAULT_VIBRATE:僅震動默認。DEFAULT_LIGHTS:僅閃光默認。由於涉及硬件訪問,記得在 AndroidManifest.xml 中補上權限聲明:
<!-- 閃光燈權限 -->
<uses-permission android:name="android.permission.FLASHLIGHT" />
<!-- 振動器權限 -->
<uses-permission android:name="android.permission.VIBRATE" />
這部分僅是屬性設置,加上多數場景直接用系統默認即可,就不再單獨提供示例代碼。
通知是 Android 中出鏡率極高的能力。它讓應用在用戶沒有打開你的 App 時,依然具備主動觸達與交互的可能,某種程度上是提升留存的重要手段。
從實踐角度補充幾點:一是通知 ID 要規劃清楚,同一業務流復用同一 ID 才能實現平滑更新;二是 setAutoCancel(true) 幾乎總該打開,否則用戶點擊後通知仍掛在狀態列,體驗很差;三是 PendingIntent 的 flag 選 FLAG_UPDATE_CURRENT 通常最省心;四是自定義 RemoteViews 能用的控件與屬性相當有限,複雜布局要在真機上反覆驗證。
開啟 ListView 側邊快速滾動滑塊:一行屬性搞定 fastScroll
不少開發者不知道 ListView 右側那個快速滾動滑塊(fast scroll thumb)該怎麼啟用,其實只要一行設定。 用 XML 布局的話,在 ListView
Android Touch 事件分發機制完整解析:從 ViewRoot 到 onClick
理解 Touch 事件的分發流程,是掌握 Android UI 開發的一道分水嶺。本文以一個簡單範例為起點,逐層追進原始碼,把「手指點一下螢幕」到「onClick 被呼叫
圖文並茂:將 Eclipse 專案完整遷移到 Android Studio 的實戰教學
前言近來 Android Studio(以下簡稱 AS)的正式版正式推出,可說是風頭正勁。最主要的原因,我想在於 Android 是 Google 自家的產品,而 AS
Android 調試工具 DDMS 使用詳解
DDMS 全稱 Dalvik Debug Monitor Service,是 Android 開發中最基礎的一套診斷工具。官方文檔見 developer.android.