編輯:關於 Android 程式設計
通知是 Android 應用與用戶溝通的重要渠道。用得好的應用,能在用戶不主動打開的情況下持續保持存在感;用得濫的應用,則會被果斷關閉通知權限甚至卸載。本文系統梳理 Android 4.4 及以下的通知體系——5.0 引入的 Material 通知樣式與通知聆聽等特性,可以另開一篇來寫。
官方對通知的描述很形象:它像一個新聞渠道,在用戶注意力不在你這裡的時候,把重要事件告訴他;也像一份日誌,記錄下用戶錯過的那些事。通知與 Service、BroadcastReceiver、Intent 關係密切,幾乎是所有常駐類應用的標配。
一條通知至少包含:
Android 4.1 之後支持通知擴展:可以展示消息的前幾行,或展示一張大圖預覽。用戶通過雙指捏合或滑動,就能在基礎佈局與擴展佈局之間切換。系統為單條通知提供了兩種現成模板——文本(BigTextStyle)與圖片(BigPictureStyle),可直接復用。

結構標註對應如下:
通知底部可以放置操作按鈕,讓用戶直接在通知欄完成最常見的操作,不必打開應用。配合「滑動清除」,能顯著提升處理通知的效率。
但按鈕不是越多越好——每多一個,用戶的認知負擔就重一分。官方的建議是:只放最重要、最有意義的一兩個。
合適的 action 特徵:
應當避免的 action:
官方給的三條設計原則是:個性化(用頭像而非純圖標)、跳轉到正確的位置、設置合適的優先級。
優先級通過 setPriority(int pri) 指定,取值如下:
Notification.PRIORITY_DEFAULT // 0 Notification.PRIORITY_HIGH // 1 Notification.PRIORITY_LOW // -1 Notification.PRIORITY_MAX // 2 Notification.PRIORITY_MIN // -2
只有 HIGH 及以上才可能在狀態欄浮出提示,濫用會讓用戶迅速學會「無視所有通知」。
很多老教程會這樣寫:
Notification notification = new Notification(
R.drawable.ic_launcher, getText(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.hello_world),
getText(R.string.hello_world), pendingIntent);
startForeground(1, notification);
這段代碼在當時沒問題,但今天必須明確:setLatestEventInfo() 已被廢棄。官方推薦使用 support-v4 包中的 NotificationCompat.Builder,它不僅API現代,還能在低版本系統上做兼容降級。
三個屬性是必須設置的:小圖標、標題、內容文本。
private NotificationManager manager;
NotificationCompat.Builder notifyBuilder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 獲取系統通知服務
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
/** 顯示最簡單的通知,以下三個 set 方法是必須的 */
public void simNotification(View view) {
notifyBuilder = new NotificationCompat.Builder(this)
/* 小圖標 */
.setSmallIcon(R.drawable.ic_launcher)
/* 標題 */
.setContentTitle("通知")
/* 詳細文本 */
.setContentText("Hello world");
manager.notify(100, notifyBuilder.build());
}

關鍵在於 PendingIntent——它是「授權他人代表你執行某個 Intent」的票據。
/** 點擊跳轉到指定 Activity */
public void largePicture(View view) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 點擊後要開啟的目標
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
notifyBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(bitmap) // 大圖標
.setSmallIcon(R.drawable.ic_launcher) // 小圖標(必須)
.setContentTitle("通知")
.setContentText("Hello world")
.setWhen(System.currentTimeMillis()) // 通知時間
.setTicker("來自問月的祝福") // 狀態欄滾動提示
.setOngoing(true) // 常駐,無法左右滑動清除
.setAutoCancel(true) // 點擊後自動消失
.setNumber(2) // 顯示數量,類似 QQ 的合併計數
.setContentIntent(pendingIntent); // 綁定點擊行為
manager.notify(121, notifyBuilder.build());
}
關於 setOngoing(true):它適合音樂播放、導航、下載這類需要常駐的通知,但代價是必須在合適時機調用 manager.cancel() 清除,否則會一直掛在通知欄裡被用戶詬病。
效果類似系統截圖預覽,使用 BigPictureStyle:
/** 類似於系統截圖的效果 */
public void comNotification(View view) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
notifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("通知")
.setContentText("Hello world")
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.setNumber(2);
NotificationCompat.BigPictureStyle bigPictureStyle =
new NotificationCompat.BigPictureStyle();
bigPictureStyle.bigPicture(bitmap);
notifyBuilder.setStyle(bigPictureStyle);
manager.notify(121, notifyBuilder.build());
}

唯一需要注意的是:加載圖片不要放在主線程(此處僅為演示)。真實場景中,網絡圖片應該先異步下載並按目標尺寸降採樣,否則動輒幾 MB 的 Bitmap 很容易引發 OOM。
場景:一個帶「稍后提醒」和「忽略」兩個按鈕的通知,點擊後交由 IntentService 處理。
/** 創建一個類似於日歷事件的 notification */
public void add_action(View view) {
myIntent = new Intent(getApplicationContext(), MyIntentService.class);
myIntent.putExtra(myConstants.EXTRA_MESSAGE, "來自問月的祝福");
myIntent.setAction(myConstants.ACTION_PING);
myIntent.putExtra(myConstants.EXTRA_TIMER, 1000);
startService(myIntent);
}
IntentService 的實現:
package me.androiddemo.canglangwenyue.test;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class MyIntentService extends IntentService {
private NotificationManager manager;
private String message;
private int mMills;
NotificationCompat.Builder builder;
public MyIntentService() {
// super 中傳入的是工作線程的名稱,用於標識
super("me.androiddemo.canglangwenyuet.test");
}
@Override
protected void onHandleIntent(Intent intent) {
message = intent.getStringExtra(myConstants.EXTRA_MESSAGE);
mMills = intent.getIntExtra(myConstants.EXTRA_TIMER, myConstants.DEFAULT_TIMER_DURATION);
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String action = intent.getAction();
issueNotification(intent, message);
if (action.equals(myConstants.ACTION_PING)) {
issueNotification(intent, message);
} else if (action.equals(myConstants.ACTION_SNOOZE)) {
notificationManager.cancel(myConstants.NOTIFICATION_ID);
issueNotification(intent, "");
} else if (action.equals(myConstants.ACTION_DISMISS)) {
notificationManager.cancel(myConstants.NOTIFICATION_ID);
}
}
private void issueNotification(Intent intent, String msg) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 「忽略」按鈕
Intent dissmissIntent = new Intent(this, MyIntentService.class);
dissmissIntent.setAction(myConstants.ACTION_DISMISS);
PendingIntent disIntent = PendingIntent.getService(this, 0, dissmissIntent, 0);
// 「稍后提醒」按鈕
Intent snoozeIntent = new Intent(this, MyIntentService.class);
snoozeIntent.setAction(myConstants.ACTION_SNOOZE);
PendingIntent snoopIntent = PendingIntent.getService(this, 0, snoozeIntent, 0);
builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Information")
.setContentText("lalallalala")
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.addAction(R.drawable.ic_launcher, "Dismiss", disIntent)
.addAction(R.drawable.ic_launcher, "snooze", snoopIntent);
Intent resultIntent = new Intent(this, MainActivity2.class);
resultIntent.putExtra(myConstants.EXTRA_MESSAGE, msg);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
startTimer(mMills);
}
/** 這裡只是簡化演示,真實項目請用 AlarmManager 或 JobScheduler */
private void startTimer(int mMills) {
try {
Thread.sleep(mMills);
} catch (Exception e) {
Log.d(myConstants.DEBUG_TAG, "ERROR");
}
issueNotification(builder);
}
private void issueNotification(NotificationCompat.Builder builder) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(myConstants.NOTIFICATION_ID, builder.build());
}
}

這裡有兩個要點:IntentService 的構造器必須調用 super(String) 傳入線程名;示例中的 Thread.sleep 只能用於演示,正式環境請改用 AlarmManager、JobScheduler 或 WorkManager 做定時。
通過 RemoteViews 加載自定義 XML,再用 setContent() 綁定即可。
/** 自定義 notification 樣式 */
public void Cus_Notification(View view) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.customnotification);
remoteViews.setImageViewResource(R.id.imageView, R.drawable.psb);
remoteViews.setTextViewText(R.id.textView, "Your Haven");
remoteViews.setTextViewText(R.id.textView2, "YUI");
remoteViews.setTextViewText(R.id.textView3, "豆瓣-FNM-我的紅心 MHZ");
remoteViews.setViewVisibility(R.id.my_large_button, View.VISIBLE);
notifyBuilder = new NotificationCompat.Builder(this)
.setContent(remoteViews)
.setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL))
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("通知")
.setTicker("Your Haven")
.setContentText("Hello world")
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_DEFAULT)
.setOngoing(true);
Notification noty = notifyBuilder.build();
noty.contentView = remoteViews;
manager.notify(313, noty);
}

示例只放了圖片和三個文本,可以繼續擴展成含 ImageButton 的版本,並通過 BroadcastReceiver 響應點擊。要注意 RemoteViews 支持的控件類型有限(不支持自定義 View),且 setSmallIcon 仍然必須設置,否則在部分系統上通知不顯示。
/** 有進度條的 notification */
public void Pro_Notification(View view) {
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notifyBuilder = new NotificationCompat.Builder(this);
notifyBuilder.setContentTitle("Picture Download")
.setContentText("Download in progress")
.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher);
// 在後台線程模擬耗時操作
new Thread(new Runnable() {
@Override
public void run() {
for (int incr = 0; incr <= 100; incr += 5) {
// 前兩個參數:最大值、當前進度;第三個 false 表示確定的進度
notifyBuilder.setProgress(100, incr, false);
manager.notify(0, notifyBuilder.build());
try {
Thread.sleep(5 * 1000); // 模擬耗時
} catch (InterruptedException e) {
Log.d("NOTIFICATION", "sleep failure");
}
}
// 循環結束,更新為完成狀態並移除進度條
notifyBuilder.setContentText("Download complete")
.setProgress(0, 0, false);
manager.notify(213, notifyBuilder.build());
}
}).start();
}

實際使用時,把 incr 換成真實的下載進度即可;不確定進度的場景可傳 setProgress(0, 0, true) 使用不確定模式的轉圈樣式。另外,若頻繁更新進度,記得控制刷新頻率(例如每 200ms 一次),逐字節刷新反而會拖慢下載。
無論哪種通知,步驟都是同一套:
第一步,獲取 NotificationManager。
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
第二步,實例化 Builder。
notifyBuilder = new NotificationCompat.Builder(this)
第三步,設置屬性。其中前三個(smallIcon、contentTitle、contentText)必填:
notifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("通知")
.setContentText("Hello world")
.setWhen(System.currentTimeMillis())
.setTicker("來自問月的祝福")
.setAutoCancel(true)
/**
* 默認效果:
* Notification.DEFAULT_ALL 鈴聲、閃光、震動均用系統默認
* Notification.DEFAULT_SOUND 系統默認鈴聲
* Notification.DEFAULT_VIBRATE 系統默認震動
* Notification.DEFAULT_LIGHTS 系統默認閃光
*/
.setDefaults(Notification.DEFAULT_VIBRATE)
.setOngoing(true)
.setNumber(2);
第四步,發出通知。
manager.notify(100, notifyBuilder.build());
常用屬性方法一覽:
setDefaults(int):添加聲音、閃燈、震動,可組合使用;setVibrate(long[] pattern):自定義震動節奏,需配合 VIBRATE 權限;setSound(Uri):自定義鈴聲;setPriority(int):設置優先級;setOngoing(boolean):設為 true 則為常駐通知,無法滑動清除,必須顯式 cancel;setProgress(int, int, boolean):設置進度條。1. notify 的 id 要規劃好。同一 id 的通知會互相覆蓋。同類通知用固定 id(實現「更新」),不同類通知用不同 id(實現「並存」)。
2. 別忘了通知權限。Android 5.0 起通知在系統設置中可被單獨關閉;8.0(API 26)起必須先創建 NotificationChannel,否則通知完全不顯示。這是本篇之後必須補的一課。
3. PendingIntent 的 requestCode 與 flag 要謹慎。多個 PendingIntent 若 requestCode 相同、Intent 的 action/data 也相同,系統會認為是同一個並復用,導致點擊行為串台。給不同按鈕分配不同 requestCode 是最省事的避坑方式。
4. 常駐通知要「有始有終」。用 setOngoing(true) 就要相應地在任務結束時 cancel,否則用戶只能去系統設置裡手動清除。
示例 Demo 下載:https://download.csdn.net/detail/u010835702/8241469
Android 單片機與藍牙模塊通信實例:打造紅綠燈控制 App
作為畢業設計,需要製作一個簡單的藍牙 App 來與單片機交互。透過參考資料並反覆調試,問題最終順利解決,下面把完整的實現思路分享給大家。 一、Android 藍牙編程基礎
Android Context 到底是什麼?一次講清楚它的由來、數量與關係
什麼是 Context? 一個 Context 意味著一個「場景」,而場景就是我們與軟體互動的過程。當你使用微信時,場景包含聊天介面、通訊錄、朋友圈,以及背後支撐它們的那
新浪微博客戶端(七):ListView 圖片異步載入與記憶體快取
為什麼要異步載入 每一則微博都有使用者頭像,內容中還可能帶圖片。如果在載入列表的同時同步載入圖片,會有兩個明顯問題:一是介面會卡住不動,使用者體驗很差;二是 Androi
Android Master Key 漏洞解析:成因、風險與修復概念
Android Master Key 漏洞,官方編號 ANDROID-8219321,是早期 Android 簽名驗證機制中的重大安全問題。它讓攻擊者有機會在 APK