編輯:關於 Android 程式設計
用過 Android 手機的人對通知欄都不陌生。本文把通知的建立、點擊回應、取消,以及進場提示的各種細節整理成一份可查的筆記。
通知可以在 Activity、廣播接收器或 Service 中建立。實務上通常在 App 退到背景後才發通知,所以很少寫在 Activity 裡。
API Level 11 及以前(已廢棄)
// 獲得通知管理器
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 創建通知對象,參數依次為通知圖標、ticker(通知欄上一閃而過的信息)、通知創建時間
Notification notification = new Notification(R.drawable.ic_launcher,
"This is ticker text", System.currentTimeMillis());
// 設置通知布局,參數依次為 Context、通知標題、通知正文、PendingIntent
notification.setLatestEventInfo(this, "This is content title",
"This is content text", null);
// 顯示通知,參數依次為唯一的 id、通知對象
manager.notify(1, notification);
API Level 12 ~ 15
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this)
.setAutoCancel(true)
.setContentTitle("title")
.setContentText("describe")
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification = builder.getNotification();
manager.notify(1, notification);
API Level 16 及以上
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
.setAutoCancel(true)
.setContentTitle("title")
.setContentText("describe")
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.build();
manager.notify(1, notification);
三者的差異只在 Builder 產生 Notification 的方式:new Notification(...) → getNotification() → build()。Android 8.0 之後還必須再建立 NotificationChannel,否則通知根本不會顯示,這一點稍後補充。
點擊行為靠 PendingIntent 承接。它需要先包一個 Intent,再用 PendingIntent.getActivity()、getBroadcast() 或 getService() 決定點擊後要啟動 Activity、送廣播還是啟動服務。
這三個靜態方法的參數一致:Context、requestCode(一般傳 0)、Intent,以及 flag。flag 有四種可選:
FLAG_ONE_SHOT:只可使用一次,用過即失效FLAG_NO_CREATE:若不存在對應 PendingIntent 就回傳 null,不新建FLAG_CANCEL_CURRENT:若已存在則先取消,再建立新的FLAG_UPDATE_CURRENT:若已存在則更新其 extras,保留原物件建立好之後透過 setContentIntent() 掛上去:
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(MainActivity.this, TestActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new Notification.Builder(this)
.setAutoCancel(true)
.setContentTitle("title")
.setContentText("describe")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.build();
manager.notify(1, notification);
setAutoCancel(true) 的意義是:使用者點了通知之後自動把它從通知欄移除。若不加,通知會一直留在那裡直到你手動取消。
傳入建立通知時使用的那個 id 即可:
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(1);
若要一次清掉該 App 發出的全部通知,改用 manager.cancelAll()。
1. 播放提示音
// 音頻 Uri
Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones"));
setSound(soundUri);
2. 手機振動
vibrate 接受一個長整型陣列,單位為毫秒,偶數索引代表靜止時長、奇數索引代表振動時長:
// 靜止 0 秒、振動 1 秒、靜止 1 秒、振動 1 秒
long[] vibrate = {0, 1000, 1000, 1000};
setVibrate(vibrate);
需另外在 manifest 宣告權限:
<uses-permission android:name="android.permission.VIBRATE"/>
3. 呼吸燈閃爍
涉及三個屬性:ledARGB 控制顏色、ledOnMS 控制亮起時間、ledOffMS 控制熄滅時間,透過 setLights() 一次設定:
setLights(Color.BLUE, 1000, 1000);
這行程式碼讓 LED 以藍色每秒明滅一次。
4. 懶人做法:全部交給系統
.setDefaults(Notification.DEFAULT_ALL)
設成預設值後,鈴聲、振動與呼吸燈的行為都跟隨使用者目前的情景模式與設定,不必自己一個個配。
要注意的是,鈴聲、振動與呼吸燈都必須在真機上才能驗證,模擬器看不出效果。
本文的三段寫法對應的是較早期的 API。若你在 Android 8.0 以上的裝置上發現通知完全不顯示,原因幾乎一定是少了 Channel:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"my_channel", "我的通知", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
建立通知時再用 setChannelId("my_channel") 指定即可。此外 Android 13 起發送通知需要 POST_NOTIFICATIONS 執行期權限,而 setLatestEventInfo()、setSound() 這類直接下指令的寫法也早已被 Builder 的串接式 API 取代——新專案請直接以 Builder 加 Channel 的組合為起點。
Android 自訂 Dialog 三步驟實作教學
寫 Android 應用幾乎一定會碰到「系統預設 Dialog 樣式跟自家設計稿搭不上」的狀況。還好自訂 Dialog 只要三個步驟: 撰寫繼承 Dialog 的 Ja
Android 百度地圖添加覆蓋物與彈窗顯示實作
實作目標 本文示範如何在 Android 百度地圖中新增覆蓋物 Marker,並在點擊 Marker 後顯示 InfoWindow 與自訂商家資訊面板。範例重點包含地圖初
QQ 第三方登錄實戰:讓使用者快速進入 App
前言第三方登入已成為許多應用的常見功能,使用者不必輸入帳號密碼即可快速進入 App。本文以 QQ 登入為例,說明 Android 端的整合流程。準備工作前往騰訊開放平台,
基於百度定位 SDK 實時計算移動距離的完整實現
前段時間因項目需求,我通過百度定位 SDK 實現了一個實時更新行駛距離的程序(類似出租車上的里程表)。看似簡單的「顯示當前位置」背後,要真正做到「實時累加移動距離」,其實