編輯:關於 Android 程式設計
本文整理 Android 開發中 Notification 通知的各種使用方法。閱讀之後,你應該能掌握從最基本的提示到自定義樣式、進度條的完整實作。以下內容主要針對 Android 4.4 以下的版本,並在文末說明後續版本的差異。
很多人最熟悉的做法大概是這樣:
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);
這是在 Service 中啟動一個通知。但請記住:這種寫法已經過時,Google 官方不再建議使用。官方推薦改用 support v4 套件中的 NotificationCompat.Builder,透過它我們可以設定各種屬性,並且獲得跨版本的相容性。
一個 Notification 物件必須包含三項內容:
一個小圖示,以 setSmallIcon() 設定。
一個標題,以 setContentTitle() 設定。
一段詳細文字,以 setContentText() 設定。
這三項是必要條件,其餘則依需求擴充。
private NotificationManager manager;
private 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());
}
把 simNotification 綁到一顆 Button 上,最簡單的通知就完成了。
/** 點擊跳轉到指定 Activity */
public void jumpNotification(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) // 顯示通知數量
.setContentIntent(pendingIntent); // 點擊行為
manager.notify(121, notifyBuilder.build());
}
這裡有幾個屬性值得留意:setOngoing(true) 會讓通知無法用手勢滑掉,適合音樂播放器、導航這類需要常駐的場景,但相對地你必須自行呼叫 cancel() 清除。setNumber() 則是在通知上顯示一個數字,常用來合併同類通知的數量提示。
類似系統截圖那種佔滿寬度的大圖效果:
/** 類似系統截圖的效果 */
public void bigPictureNotification(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());
}
唯一要注意的是:載入圖片最好不要在主執行緒進行,這裡只是為了示範方便。實務上應該先解壓縮或下載完成,再把結果送進通知。
想要做出「行事曆事件提醒」那種帶有操作按鈕的通知,需要搭配 IntentService。
/** 建立一個類似行事曆事件的通知 */
public void addAction(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 的實作如下。要特別注意建構子的重載,super() 裡傳的字串是背景執行緒的名稱。
package me.androiddemo.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;
private NotificationCompat.Builder builder;
public MyIntentService() {
// super 呼叫是必須的,IntentService 啟動的背景執行緒會用這個字串標記
super("me.androiddemo.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 dismissIntent = new Intent(this, MyIntentService.class);
dismissIntent.setAction(myConstants.ACTION_DISMISS);
PendingIntent disIntent =
PendingIntent.getService(this, 0, dismissIntent, 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);
}
private void startTimer(int mills) {
try {
Thread.sleep(mills);
} 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());
}
}
這裡只實作了一個簡陋的計時器,僅供參考。正式環境請用 AlarmManager 或 WorkManager,在 IntentService 裡 sleep 會讓背景執行緒被長期佔用,並不適合真實的排程需求。
只要透過 RemoteViews 載入你的 XML 布局,再用 setContent() 掛上去即可。
/** 自定義通知樣式 */
public void customNotification(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);
}
這裡只加了一個 ImageView 和三個 TextView,你可以進一步擴充,例如加入 ImageButton 並透過 BroadcastReceiver 監聽點擊。
/** 有進度條的通知 */
public void progressNotification(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) {
// 設定進度最大值、目前完成百分比、以及「確定性」狀態
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();
}
概念就是在一個背景執行緒裡週期性推進進度,結束後再發一則新通知顯示完成。實務上把 Thread.sleep() 換成實際的下載進度回呼即可。
1. 取得 NotificationManager 實例,也就是取得狀態列通知權。
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
2. 建立 Builder
notifyBuilder = new NotificationCompat.Builder(this);
3. 設定各種屬性
// 前三個屬性必須設定
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("通知")
.setContentText("Hello world")
// 其餘為可選
.setWhen(System.currentTimeMillis())
.setTicker("來自問月的祝福")
.setAutoCancel(true)
// 預設效果可選:DEFAULT_ALL / DEFAULT_SOUND / DEFAULT_VIBRATE / DEFAULT_LIGHTS
.setDefaults(Notification.DEFAULT_VIBRATE)
.setOngoing(true)
.setNumber(2);
4. 發出通知
manager.notify(100, notifyBuilder.build());
setDefaults(int):以系統預設值加入鈴聲、閃燈、震動,是最省事的做法。setVibrate(long[]):自訂震動節奏。setSound(Uri):自訂提示音。setPriority(int):設定優先級,會影響通知在狀態列的排序與是否以浮動形式出現。setOngoing(boolean):設為 true 則為常駐通知,無法滑動清除。setProgress(int max, int progress, boolean indeterminate):設定進度條,第三個參數為 true 時顯示不確定模式的循環進度。
如果你是在維護新專案,這一節比前面所有內容都重要。
通知渠道(NotificationChannel)是強制項。從 Android 8.0(API 26)開始,所有通知都必須歸屬於一個渠道,否則通知根本不會顯示。渠道一旦建立,其重要程度、提示音、震動等行為就由使用者掌控,開發者無法事後修改:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"my_channel_id", "我的通知渠道", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
接著在 Builder 中指定 .setChannelId("my_channel_id")。
其他幾個關鍵差異:
小圖示必須使用單色的透明向量圖,用彩色圖會被系統渲染成一塊白色方塊。
Android 12 之後,自定義通知內容會被限制在標準模板內,RemoteViews 的自由度大幅降低。
Android 13 起,發送通知需要 POST_NOTIFICATIONS 執行期權限。
建立通知的程式碼應統一收斂到 NotificationManagerCompat.notify(),它會自動處理版本差異。
至於全螢幕通知、鎖定畫面通知等,本質上都是換湯不換藥——依需求設定對應屬性並查閱官方文件即可。
米 SIM 卡怎麼啟用?小米虛擬卡的開通流程與注意事項
「米 SIM」這個名稱對不少使用者來說還很陌生,更別說要去開通啟用了。它其實是小米自家打造的一種不必插實體卡就能上網的服務。以下用圖文把開通流程走一遍。 米 SIM 的開
Android 手勢識別實作:GestureOverlayView 與 GestureLibrary 用法
Android 的 android.gesture 套件提供了手勢繪製與識別能力。典型流程包含建立繪圖區、監聽手勢輸入、儲存手勢樣本,以及比對使用者新畫出的手勢。以下概念
QQ 第三方登錄實戰:讓使用者快速進入 App
前言第三方登入已成為許多應用的常見功能,使用者不必輸入帳號密碼即可快速進入 App。本文以 QQ 登入為例,說明 Android 端的整合流程。準備工作前往騰訊開放平台,
Android 7.0 PowerManagerService 解析:WakeLock 的使用與流程
在行動裝置上,電量是有限資源。Android 為了節省電力,會在空閒時讓系統進入休眠。但系統中有許多執行緒與服務可能仍需要執行重要工作,因此需要一套機制來表達「目前仍有任