編輯:Android 開發實例
手機來了簡訊而你沒點開,狀態欄上方會留一個小圖示提醒你——這就是 Notification。想在自己的應用裡做類似的事,就得把 Notification 這套 API 摸清楚。
麻煩的是 Android 的 Notification 經過多次改版,網路上抄來抄去的寫法有些早已被棄用。下面用同一個 Demo 實作四種建立方式,並標明各自適用的 API 等級。



無論哪一種寫法,流程都是三步:取得 NotificationManager → 建立 Notification → 呼叫 notify()。
其中 NotificationManager 是系統服務,用 getSystemService(Context.NOTIFICATION_SERVICE) 取得。而 PendingIntent 則是個容易卡住初學者的概念——它和 Intent 很像,但重點在「不是現在就執行」。使用者點擊通知才會觸發它,系統需要一個「授權票券」在未來那個時間點代 your app 啟動某個 Activity,這就是 PendingIntent 存在的理由。
package net.loonggg.notification;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RemoteViews;
public class MainActivity extends Activity {
private static final int NOTIFICATION_FLAG = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void notificationMethod(View view) {
// 取得系統的通知管理器
NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
switch (view.getId()) {
// 寫法一:預設通知(舊式寫法,已被棄用但相容性最好)
case R.id.btn1:
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, MainActivity.class), 0);
// Notification notify1 = new Notification(R.drawable.message,
// "TickerText:" + "您有新短消息,請注意查收!", System.currentTimeMillis());
Notification notify1 = new Notification();
notify1.icon = R.drawable.message;
notify1.tickerText = "TickerText:您有新短消息,請注意查收!";
notify1.when = System.currentTimeMillis();
notify1.setLatestEventInfo(this, "Notification Title",
"This is the notification message", pendingIntent);
notify1.number = 1;
// FLAG_AUTO_CANCEL:使用者點擊後通知自動清除
notify1.flags |= Notification.FLAG_AUTO_CANCEL;
// 透過管理器發出通知。id 不同則每次都會新增一則
manager.notify(NOTIFICATION_FLAG, notify1);
break;
// 寫法二:Notification.Builder(API 11 起可用)
case R.id.btn2:
PendingIntent pendingIntent2 = PendingIntent.getActivity(
this, 0, new Intent(this, MainActivity.class), 0);
Notification notify2 = new Notification.Builder(this)
.setSmallIcon(R.drawable.message) // 狀態欄小圖,建議 24x24
.setTicker("TickerText:" + "您有新短消息,請注意查收!")
.setContentTitle("Notification Title")
.setContentText("This is the notification message")
.setContentIntent(pendingIntent2)
.setNumber(1)
.getNotification(); // API 16 起可用 build() 取代
notify2.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTIFICATION_FLAG, notify2);
break;
// 寫法三:Notification.Builder + build()(API 16 起)
case R.id.btn3:
PendingIntent pendingIntent3 = PendingIntent.getActivity(
this, 0, new Intent(this, MainActivity.class), 0);
Notification notify3 = new Notification.Builder(this)
.setSmallIcon(R.drawable.message)
.setTicker("TickerText:" + "您有新短消息,請注意查收!")
.setContentTitle("Notification Title")
.setContentText("This is the notification message")
.setContentIntent(pendingIntent3)
.setNumber(1)
.build();
notify3.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTIFICATION_FLAG, notify3);
break;
// 寫法四:自訂版面
case R.id.btn4:
Notification myNotify = new Notification();
myNotify.icon = R.drawable.message;
myNotify.tickerText = "TickerText:您有新短消息,請注意查收!";
myNotify.when = System.currentTimeMillis();
myNotify.flags = Notification.FLAG_NO_CLEAR; // 不允許自動清除
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.my_notification);
rv.setTextViewText(R.id.text_content, "hello wrold!");
myNotify.contentView = rv;
Intent intent = new Intent(Intent.ACTION_MAIN);
PendingIntent contentIntent = PendingIntent.getActivity(this, 1, intent, 1);
myNotify.contentIntent = contentIntent;
manager.notify(NOTIFICATION_FLAG, myNotify);
break;
case R.id.btn5:
// 清除 id 為 NOTIFICATION_FLAG 的通知
manager.cancel(NOTIFICATION_FLAG);
// 清除所有通知
// manager.cancelAll();
break;
default:
break;
}
}
}<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="預設通知(已被棄用,但通用)" />
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="預設通知(API11 之後可用)" />
<Button
android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="預設通知(API16 之後可用)" />
<Button
android:id="@+id/btn4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="自定義通知" />
<Button
android:id="@+id/btn5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="notificationMethod"
android:text="清除通知" />
</LinearLayout>my_notification.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="vertical" >
<TextView
android:id="@+id/text_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
</LinearLayout>寫法一(setLatestEventInfo)在 API 23 已被移除,現在編譯不會過。留著是為了理解演進脈絡——它說明瞭通知的最小必要元素是什麼:icon、tickerText、when、contentIntent。
寫法二、三差別只在 getNotification() 與 build(),而這兩個方法本身也已進入棄用階段。目前的正確做法是全程使用 Notification.Builder 的 build(),並額外加上三件事:
setSmallIcon 在新版系統是必填,缺少會導致通知靜默失敗。寫法四值得單獨說明的是 RemoteViews:它並不是普通的 View,而是一個「跨行程的版面描述」。系統行程要畫你的通知,所以只能傳遞受限的操作集合(設定文字、圖片等),不能塞自訂 View 進去。這也是自訂通知版面能用的控制項與屬性都比一般版面少的根本原因。新版 Android 對自訂通知的面板也有尺寸限制,過度客製化的版面會被系統裁切。
最後一個實務建議:notify() 的第一個參數(id)決定通知的身分。同一個 id 重複呼叫會更新而非新增,這在實作「下載進度」這類需要持續更新單一通知的場景非常有用;反之若每次都傳不同 id,使用者就會被一堆通知洗版。
Android MediaPlayer 使用指南:播放控制、進度條與快轉倒轉
要在 App 裡播放音訊或影片,Android 提供了多種途徑,其中最直接的就是 MediaPlayer。它屬於系統內建的媒體播放服務,透過這個類別,你能以幾行程式碼完成
使用 PHP for Android 與 SL4A 打造 Android 應用
PHP for Android 讓開發者能在 Android 上以 PHP 撰寫腳本,搭配 Scripting Layer for Android,也就是 SL4A,可快
Android 短信驗證碼注冊功能全流程實現與手機號正則校驗
注冊賬號時「填手機號 → 收驗證碼 → 提交注冊」這條路徑,幾乎每個 App 都有。本文以一個注冊頁為例,把網絡請求分層、驗證碼倒計時、Handler 線程通信、弱引用防
Android 設定裡的隱藏彩蛋是怎麼做出來的(2.3 原始碼解析)
工程師偶爾也會在系統裡藏點小趣味。Android 的「設定」中就有這樣一處:連續快速點擊「Android 版本」,會跳出一張圖;在 2.3 上是那張著名的安卓機器人塗鴉: