編輯:關於 Android 程式設計
在 Android 裡推送一條狀態列通知其實並不複雜,但真要把它用得好,牽涉到的細節卻不少。本文把通知的發送、更新、清除,以及鈴聲、振動、呼吸燈、自訂版面等常見設定一次梳理清楚。
要發出狀態列通知,一定會用到下面這兩個角色:
NotificationManager:通知的管理者,負責發送與清除通知。它是系統 Service,必須透過 getSystemService() 取得:
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification:通知本體,圖示、標題、內文、提示音、振動等參數都掛在它身上。
一則通知最基本的構成要素有三項:
· 一個 icon(狀態列上的圖示)
· 一組標題與展開後的內文
· 一個 PendingIntent(點擊通知後要跳去哪裡)
其餘都是加分項:狀態列頂部的 ticker 提示文字、提示音、振動、指示燈閃爍等等。
呼叫 NotificationManager.notify(int, Notification)。第一個參數是這則通知的唯一識別碼,第二個是通知物件本身。
重新呼叫 setLatestEventInfo() 修改內容,再執行一次 notify() 並沿用同一個 ID 即可。實務上很常見:短信剛跳出還沒看,第二封又來了,這時更新原本的通知比再疊一則新通知友善得多。
用 cancel(int) 搭配通知的 ID 移除單一通知;若想一次清空,則呼叫 cancelAll()。
baseNF = new Notification(); // 狀態列圖示 baseNF.icon = R.drawable.icon; // 手指下拉時,短暫顯示在狀態列頂部的文字 baseNF.tickerText = "You clicked BaseNF!"; // 採用系統預設提示音 baseNF.defaults = Notification.DEFAULT_SOUND; // 三個參數依序為:展開後的標題、展開後的內容、點擊後的跳轉 baseNF.setLatestEventInfo(Lesson_10.this, "Title01", "Content01", pd); // 正式發出通知 nm.notify(Notification_ID_BASE, baseNF);

想省事就直接用系統預設:
baseNF.defaults = Notification.DEFAULT_SOUND;
要換成自己的音檔則改用 sound:
notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
若偏好系統內建的鈴聲,可以這樣寫:
notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
這裡有個容易踩到的細節:defaults 與 sound 同時存在時,sound 會失效,系統一律播放預設鈴聲。
另外,預設情況下提示音播完一次就停。若希望它持續響到使用者有所回應(例如下拉通知列),加上 FLAG_INSISTENT:
notification.flags |= notification.FLAG_INSISTENT;
使用系統預設震動:
notification.defaults |= Notification.DEFAULT_VIBRATE;
想要自訂節奏,就改用一個 Long 陣列:
long[] vibrate = {0, 100, 200, 300};
notification.vibrate = vibrate;
陣列的意義是「等待、震、停、震……」的時間序列(毫秒):第一個值是開始震動前的等待時間,第二個是第一次震動的持續時間,第三個是之後的間隔,以此類推,長度不限。這種寫法無法做到無限循環震動。同樣地,defaults 與 vibrate 並存時以 defaults 為準。
別忘了震動需要權限:
<uses-permission android:name="android.permission.VIBRATE"></uses-permission>
使用預設燈光:
notification.defaults |= Notification.DEFAULT_LIGHTS;
自訂顏色與節奏:
notification.ledARGB = 0xff00ff00; notification.ledOnMS = 300; notification.ledOffMS = 1000; notification.flags |= Notification.FLAG_SHOW_LIGHTS;
其中 ledARGB 決定顏色,ledOnMS 是亮起的持續時間,ledOffMS 是熄滅時間。要注意燈光顏色能否呈現與硬體有關,並非每台機型都支援任意顏色。
// 提示音與震動持續循環,直到使用者回應
Notification.FLAG_INSISTENT;
// 通知被點擊後自動消失
Notification.FLAG_AUTO_CANCEL;
// 按下「清除」時不一起被清掉(某些即時通訊 App 的常駐通知就是這個效果)
Notification.FLAG_NO_CLEAR;
下面的範例涵蓋了建立、更新、清除通知,以及自訂鈴聲、自訂震動與自訂通知版面。


package com.yfz;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Lesson_10 extends Activity {
private Button bt01, bt02, bt03, bt04, bt05, bt06, bt07;
private NotificationManager nm;
private PendingIntent pd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lesson10);
init();
}
private void init() {
bt01 = (Button) findViewById(R.id.le10bt01);
bt02 = (Button) findViewById(R.id.le10bt02);
bt03 = (Button) findViewById(R.id.le10bt03);
bt04 = (Button) findViewById(R.id.le10bt04);
bt05 = (Button) findViewById(R.id.le10bt05);
bt06 = (Button) findViewById(R.id.le10bt06);
bt07 = (Button) findViewById(R.id.le10bt07);
bt01.setOnClickListener(onclick);
bt02.setOnClickListener(onclick);
bt03.setOnClickListener(onclick);
bt04.setOnClickListener(onclick);
bt05.setOnClickListener(onclick);
bt06.setOnClickListener(onclick);
bt07.setOnClickListener(onclick);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, Lesson_10.class);
pd = PendingIntent.getActivity(Lesson_10.this, 0, intent, 0);
}
OnClickListener onclick = new OnClickListener() {
private int Notification_ID_BASE = 110;
private Notification baseNF;
private int Notification_ID_MEDIA = 119;
private Notification mediaNF;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.le10bt01:
baseNF = new Notification();
baseNF.icon = R.drawable.icon;
baseNF.tickerText = "You clicked BaseNF!";
baseNF.defaults |= Notification.DEFAULT_SOUND;
baseNF.defaults |= Notification.DEFAULT_VIBRATE;
baseNF.defaults |= Notification.DEFAULT_LIGHTS;
baseNF.flags |= Notification.FLAG_INSISTENT;
baseNF.flags |= Notification.FLAG_AUTO_CANCEL;
baseNF.flags |= Notification.FLAG_NO_CLEAR;
baseNF.setLatestEventInfo(Lesson_10.this, "Title01", "Content01", pd);
nm.notify(Notification_ID_BASE, baseNF);
break;
case R.id.le10bt02:
// 沿用同一個 ID 即可原地更新內容
baseNF.setLatestEventInfo(Lesson_10.this, "Title02", "Content02", pd);
nm.notify(Notification_ID_BASE, baseNF);
break;
case R.id.le10bt03:
nm.cancel(Notification_ID_BASE);
break;
case R.id.le10bt04:
mediaNF = new Notification();
mediaNF.icon = R.drawable.icon;
mediaNF.tickerText = "You clicked MediaNF!";
mediaNF.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
long[] vir = {0, 100, 200, 300};
mediaNF.vibrate = vir;
mediaNF.setLatestEventInfo(Lesson_10.this, "Title03", "Content03", pd);
nm.notify(Notification_ID_MEDIA, mediaNF);
break;
case R.id.le10bt05:
nm.cancel(Notification_ID_MEDIA);
break;
case R.id.le10bt06:
nm.cancelAll();
break;
case R.id.le10bt07:
// 自訂展開後的版面,例如下載 App 時的進度條
Notification notification = new Notification();
notification.icon = R.drawable.icon;
notification.tickerText = "Custom!";
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom);
contentView.setImageViewResource(R.id.image, R.drawable.icon);
contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view");
notification.contentView = contentView;
// 使用自訂版面時不必再呼叫 setLatestEventInfo(),但一定要指定 contentIntent
notification.contentIntent = pd;
nm.notify(3, notification);
break;
}
}
};
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button android:id="@+id/le10bt01" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="BaseNotification" />
<Button android:id="@+id/le10bt02" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="UpdateBaseNotification" />
<Button android:id="@+id/le10bt03" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="ClearBaseNotification" />
<Button android:id="@+id/le10bt04" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="MediaNotification" />
<Button android:id="@+id/le10bt05" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="ClearMediaNotification" />
<Button android:id="@+id/le10bt06" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="ClearALL" />
<Button android:id="@+id/le10bt07" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="CustomNotification" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="3dp">
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp" />
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#000" />
</LinearLayout>
補充一句:以上寫法屬於較早期的 Notification API 風格,在後續 Android 版本中 setLatestEventInfo() 與部分欄位已被 Builder 模式取代,實際專案請以目前 SDK 的建議做法為準,但觀念與參數設計思路是相通的。
Android 自定義手勢密碼簡易版實作
簡易九宮格手勢若要快速實作手勢密碼,可先建立一個自訂 View,在畫布上畫出九個圓點。每個圓點需要記錄編號、座標與是否被選中,當手指滑過時,就將符合範圍的圓點加入連線。初
動手實作 Android 硬體抽象層(HAL)程式碼
前面已經寫過了 Java 層的應用與系統服務,這一步要往下走進 native 層,實作一個對應自訂硬體的 HAL 模組。HAL 的本質是一套「有強制規範的動態連結庫」,
自定義 View 實作雷達式搜索動畫:擴散圓與旋轉游標
藍牙搜索、附近熱點掃描這類功能,如果只丟一個轉圈圈會顯得很敷衍。做一個有擴散波紋、有中心圖示緩慢旋轉的雷達效果,成本低但質感提升明顯。本文用一個自定義 View 把整個動
Android 4.4 SystemUI 源碼分析(一):從 SystemUIService 到 PowerUI
以下分析基於 MTK 的 Android 4.4 原生 SystemUI。MTK 版本與 Google 原生版本有細微差異,但整體架構是一致的。 這是 SystemUI