編輯:關於 Android 程式設計
用過這麼多 App,通知提醒的表現方式其實差異很大。本文整理幾種實務上常被忽略的 Notification 進階玩法,並順著 NotificationManager.notify() 走一趟源碼,理解系統到底是怎麼把一條通知推到狀態列上的。
把 setOngoing(true) 打開之後,通知會持續停留在通知欄,直到被 cancel 或應用退出。這特性很適合需要即時刷新內容的場景,例如計時器——每秒更新一次剩餘時間。

實作上非常直觀,用 Timer 每 1000ms 觸發一次重建通知的動作即可:
private Timer timer;
private TimerTask task;
if (timer != null) return;
timer = new Timer("time");
task = new TimerTask() {
@Override
public void run() {
showDynamicNotification();
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
private void showDynamicNotification() {
mBuilder = new NotificationCompat.Builder(NotificationActivity.this);
RemoteViews view = new RemoteViews(getPackageName(), R.layout.layout_notification);
view.setTextViewText(R.id.tv_number, parseDate());
view.setImageViewResource(R.id.iv_icon, R.mipmap.ic_launcher);
Intent intent = new Intent(NOTIFY_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
NotificationActivity.this, 1000, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setTicker("you got a new message")
.setOngoing(true)
.setContent(view);
notification = mBuilder.build();
notificationManager.notify(NOTIFY_ID2, notification);
}
private String parseDate() {
SimpleDateFormat format = new SimpleDateFormat("yyyy hh:mm:ss", Locale.getDefault());
return format.format(System.currentTimeMillis());
}
Notification.Builder 是 API 11 才有的,為了向下相容,實務上通常改用 Support V4 提供的 NotificationCompat.Builder。
動態更新的關鍵在 NotificationManager.notify() 的 id 參數。這個 id 在應用內必須唯一,否則在部分 4.x 機型上會出現 PendingIntent 無法回應的怪現象(紅米上就遇過)。更新既有通知的做法是:用相同的 id 再次呼叫 notify,若舊通知仍顯示中,系統會直接更新其內容;若已被清除,則會建立一條新通知。
另外要留意,範例中用的是完全自訂的 RemoteViews,而 RemoteViews 的更新機制與一般 View 完全不同,值得另外深入研究。
FLAG_CANCEL_CURRENT:若 PendingIntent 已存在,先取消再重建。FLAG_NO_CREATE:若對應的 PendingIntent 不存在,就不建立。FLAG_ONE_SHOT:此 PendingIntent 只能使用一次。FLAG_UPDATE_CURRENT:若已存在則替換其內容,最常用。Notification 有兩種視覺風格:標準視圖(Normal View)與大視圖(Big View)。標準視圖在各版本通用;大視圖則需要 Android 4.1 以上才支援,郵件、音樂這類 App 常用它來擴展通知欄。系統透過 setStyle() 切換,一般有三種可選:
NotificationCompat.BigPictureStyle:在展開區顯示一張 256dp 高的圖。NotificationCompat.BigTextStyle:在展開區顯示一大段文字。NotificationCompat.InboxStyle:在展開區顯示多行清單式文字。
API 21 之後又多了 Notification.MediaStyle,可以做出接近主流音樂播放器的控制介面。

當然,也可以完全放棄這些預設樣式,直接自訂版面。

以下是一個自訂小視圖搭配大視圖的簡易示範:

RemoteViews smallView = new RemoteViews(getPackageName(), R.layout.layout_notification);
smallView.setTextViewText(R.id.tv_number, parseDate());
smallView.setImageViewResource(R.id.iv_icon, R.mipmap.ic_launcher);
mBuilder = new NotificationCompat.Builder(NotificationActivity.this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setNumber((int) (Math.random() * 1000))
.setTicker("you got a new message")
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
.setAutoCancel(true)
.setWhen(0)
.setPriority(NotificationCompat.PRIORITY_LOW);
intent = new Intent(NOTIFY_ACTION);
pendingIntent = PendingIntent.getBroadcast(
NotificationActivity.this, 1000, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
// 5.0 之後可讓通知出現在鎖定畫面
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
notification = mBuilder.build();
notification.contentView = smallView;
// 4.1 以上才支援大視圖
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
RemoteViews view = new RemoteViews(getPackageName(), R.layout.layout_big_notification);
view.setTextViewText(R.id.tv_name, "這是一段很長很長的文字,用來示範大視圖的排版效果");
view.setOnClickPendingIntent(R.id.btn_click_close,
PendingIntent.getBroadcast(NotificationActivity.this, 1001,
new Intent(CLICK_ACTION), PendingIntent.FLAG_UPDATE_CURRENT));
notification.bigContentView = view;
}
notificationManager.notify(NOTIFY_ID3, notification);
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:background="#ef222222"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:padding="10dp">
<FrameLayout
android:layout_height="150dp"
android:layout_width="match_parent">
<ImageView
android:id="@+id/iv_icon"
android:background="@mipmap/ic_launcher"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/tv_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ellipsize="marquee"
android:fadingedge="horizontal"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_horizontal|center_vertical"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="false"
android:singleLine="true"
android:textColor="#fff"
android:textSize="15sp">
<requestFocus />
</TextView>
<Button
android:id="@+id/btn_click_close"
android:background="#ef222222"
android:layout_gravity="center_horizontal"
android:layout_height="40dp"
android:layout_width="40dp"
android:layout_marginTop="10dp"
android:text="X"
android:textSize="30sp" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
setTicker 在 API 21 之後已被標記為 Deprecated,實際上不再有效果。
setDeleteIntent 是 API 11 才新增的監聽刪除回呼,但要注意:一旦 setAutoCancel(true),這個回呼就會失效。
setPriority 用來設定通知優先級,會影響是否以浮動形式出現。
鎖定畫面顯示在 API 21 之後開放,對短信等隱私性通知可以設為隱藏,而對一般無敏感資訊的通知設為 VISIBILITY_PUBLIC,能省掉使用者解鎖再下拉的步驟,體驗提升明顯。
大視圖高度的設定有點反直覺:在最外層 LinearLayout 上設定高度是無效的,必須多包一層 FrameLayout 並在 FrameLayout 上設定高度才會生效。
跑馬燈也有陷阱:單獨使用 contentView 時,RemoteViews 中 TextView 的 marquee 屬性可以正常運作;但一旦設定了 bigContentView,連 contentView 裡的 marquee 也會一起失效,這點務必留意。
微信那種從上方滑出的提醒,在 Android 上實作起來出乎意料地簡單,關鍵是把 priority 拉到最高。

RemoteViews headsUpView = new RemoteViews(getPackageName(), R.layout.layout_heads_up_notification);
intent = new Intent(NOTIFY_ACTION);
pendingIntent = PendingIntent.getBroadcast(
NotificationActivity.this, 1000, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(NotificationActivity.this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("this is notification title test")
.setContentText("this is notification text test")
.setNumber((int) (Math.random() * 1000))
.setTicker("you got a new message")
// 必須設定 contentIntent,否則會 crash
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)
.setAutoCancel(true)
.setWhen(0);
notification = mBuilder.build();
if (Build.VERSION.SDK_INT >= 21) {
notification.priority = Notification.PRIORITY_MAX;
notification.headsUpContentView = headsUpView;
}
notificationManager.notify(NOTIFY_ID1, notification);
透過通知開啟 Activity 會牽涉到 Task 與返回堆疊的問題,有兩種典型情況值得注意。
第一種是希望一次打開整個 Task,也就是父 Activity 也一起按順序排入堆疊。但系統在建立這條堆疊之前,會先清空原本的 Task。舉例來說,你想開啟 A→B→C,而當前堆疊裡是 D 和 C,系統會先依序關掉 D 與 C,再依序開啟 A→B→C。
第二種是把 Activity 放到一個全新的獨立 Task 中,這會產生兩個 Task 堆疊。兩種做法在官方文件裡都有詳細說明。
Android 5.0 之後,使用系統圖標以外的圖片會導致狀態列圖標變成白色方塊。部分國產 ROM(如小米、錘子)自行修正了這個問題,但 HTC、三星等 ROM 仍然存在,需要額外處理。
在 2.3 環境下,直接透過 setContent(rvMain) 塞入 RemoteViews 是無效的,需要改用另一種寫法:
RemoteViews rvMain = new RemoteViews(context.getPackageName(), R.layout.notification_layout);
// TODO 設定 rvMain 內容
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContent(rvMain);
Notification notification = builder.build();
if (Build.VERSION.SDK_INT <= 10) {
notification.contentView = rvMain;
}
setContentIntent():使用者點擊通知時觸發。setFullScreenIntent():通知顯示時會被呼叫,用於懸浮式全屏提醒。setDeleteIntent():使用者清除通知時觸發,無論是點擊清除鍵還是滑動刪除(高版本)。另外,2.3 及以下版本無法處理自訂版面中的點擊事件,因此在那些版本上不必嘗試加入自訂按鈕。
以 NotificationManager.notify() 為起點來看:
INotificationManager service = getService();
...
service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id, stripped, idOut, UserHandle.myUserId());
getService() 的實作如下:
static public INotificationManager getService() {
if (sService != null) {
return sService;
}
IBinder b = ServiceManager.getService("notification");
sService = INotificationManager.Stub.asInterface(b);
return sService;
}
這裡透過 ServiceManager.getService("notification") 取得 INotificationManager 的 Binder 物件進行跨進程通訊,實體就是 NotificationManagerService。牽涉到的兩個服務——StatusBarManagerService 與 NotificationManagerService——都在 frameworks/base/services/java/com/android/server/SystemServer.java 中啟動:
class ServerThread extends Thread {
public void run() {
...
StatusBarManagerService statusBar = null;
NotificationManagerService notification = null;
...
statusBar = new StatusBarManagerService(context, wm);
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
...
notification = new NotificationManagerService(context, statusBar, lights);
ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
...
}
}
其中 system_server 進程是由 Zygote 透過 fork SystemServer 建立的。
enqueueNotificationWithTag 最終會呼叫 enqueueNotificationInternal,這才是真正的核心。以下擷取關鍵片段:
void enqueueNotificationInternal(final String pkg, final String opPkg,
final int callingUid, final int callingPid, final String tag, final int id,
final Notification notification, int[] idOut, int incomingUserId) {
// 除了 android 套件與已註冊的 listener 之外,每個套件的通知數量都有上限,
// 目的是防止 DOS 攻擊與資源洩漏
mHandler.post(new Runnable() {
@Override
public void run() {
synchronized (mNotificationList) {
// 1. 清理輸入參數,把 priority 夾在合法區間內
notification.priority = clamp(notification.priority,
Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
// 2. 計算初始分數
final int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER;
// 3. 把 Notification 包裝成 StatusBarNotification 與 NotificationRecord,
// 並嘗試處理群組通知,downloadManager 另有專屬流程
// 4. 套用本地規則
mRankingHelper.sort(mNotificationList);
// 5. 若有 smallIcon 才通知所有 listener;否則視為無效通知
if (notification.getSmallIcon() != null) {
StatusBarNotification oldSbn = (old != null) ? old.sbn : null;
mListeners.notifyPostedLocked(n, oldSbn);
}
// 6. 觸發提示效果
buzzBeepBlinkLocked(r);
}
}
});
}
notifyPostedLocked 會再 post 到工作 handler,最終透過 Binder 呼叫 NotificationListenerService。這個類別很實用,可以繼承它來監聽系統通知的各種動作。
最後的 buzzBeepBlinkLocked() 負責判斷是否需要聲音、震動與呼吸燈,職責單一但程式碼很長:
private void buzzBeepBlinkLocked(NotificationRecord record) {
...
// 判斷這條通知是否該發出聲音、震動或閃光
// 更新型通知若帶有 FLAG_ONLY_ALERT_ONCE,則不再提示
if (disableEffects == null
&& (!(record.isUpdate && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0))
&& (record.getUserId() == UserHandle.USER_ALL
|| record.getUserId() == currentUser
|| mUserProfiles.isCurrentProfile(record.getUserId()))
&& canInterrupt && mSystemReady && mAudioManager != null) {
sendAccessibilityEvent(notification, record.sbn.getPackageName());
// sound:判斷是否使用預設提示音
// vibrate:判斷是否使用自訂震動模式
// light:判斷是否使用呼吸燈
if (buzz || beep || blink) {
EventLogTags.writeNotificationAlert(record.getKey(),
buzz ? 1 : 0, beep ? 1 : 0, blink ? 1 : 0);
mHandler.post(mBuzzBeepBlinked);
}
}
}
mBuzzBeepBlinked 被 post 到工作 handler 後,會呼叫 mStatusBar.buzzBeepBlinked()。mStatusBar 是 StatusBarManagerInternal 型別,在 StatusBarManagerService 中初始化,因此最終落到:
public void buzzBeepBlinked() {
if (mBar != null) {
try {
mBar.buzzBeepBlinked();
} catch (RemoteException ex) {
}
}
}

這原本被視為 iOS 的風格,但部分 Android 機型同樣支援,例如三星與 HTC(m8t、6.0)的某些機種。小米是個特例,它會依通知數量自動生成角標,不需要額外處理。
對 HTC 與三星,一般可以靠發送 android.intent.action.BADGE_COUNT_UPDATE 廣播來達成:
public static void setBadge(Context context, int count) {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
}
public static String getLauncherClassName(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if (pkgName.equalsIgnoreCase(context.getPackageName())) {
return resolveInfo.activityInfo.name;
}
}
return null;
}
抽象工廠模式在 Android 中的應用
抽象工廠模式是什麼抽象工廠模式屬於物件建立型模式,是工廠方法模式的延伸。當系統需要建立多個產品族,且這些產品之間存在搭配關係時,抽象工廠模式特別適合。主要角色抽象工廠模式
Android Socket 與多線程聊天功能:客戶端實作
使用 Socket 與多線程可以建立簡單的聊天客戶端。手機端透過 Socket 連線到伺服器,再分別使用輸入與輸出線程處理訊息接收與傳送,从而实现基本的即時通訊。基本流程
用 Timer 讓 WebView 進度條勻速推進
用 WebView 載入網頁時,若遇到網路較慢,畫面會出現一片空白,體驗很差。加上進度條是標準解法,但直接把 onProgressChanged() 的數值塞給 Prog
非 ROOT 靜默安裝的實現思路與實踐:AIDL、反射 ServiceManager 與系統簽名
最近公司的自研系統要做一個升級服務,包含三大功能:一是系統升級,即下載 OTA 包推送到 recovery 中完成升級;二是 MCU 升級,這涉及我們自家系統的具體情況;