Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 通知機制完整教學:建立、更新、取消與大樣式顯示

編輯:進階開發

Toast 類別提供了最省事的方式來向使用者顯示提示訊息,但它並不持久——訊息在螢幕上閃個幾秒就消失了。對於真正重要、需要使用者記得的訊息,我們需要更長效的手段。

這就是 Notification 的用武之地。通知會以圖示形式出現在裝置頂部的通知列或狀態列中,使用者可以在方便時再回頭處理。

要看通知的細節,只要點開通知抽屜即可。在模擬器上,按住狀態列往下拖就能展開,這時看到的是一個高約 64sp 的標準視圖:

若資訊量較大,還可以把它擴展成一個更大的視圖,容納更多細節,最多可放六行。下圖就是這種擴展形式:

建立並發送通知

整個流程可以拆成四個步驟。

步驟一:建立通知建構器

先用 NotificationCompat.Builder 建立一個建構器,後續所有設定都透過它進行:

 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

步驟二:設定通知屬性

取得建構器後,就能指定各項屬性。其中有三項是必填的:

  • 小圖示,以 setSmallIcon() 設定
  • 標題,以 setContentTitle() 設定
  • 詳細內容,以 setContentText() 設定
 mBuilder.setSmallIcon(R.drawable.notification_icon); mBuilder.setContentTitle("Notification Alert, Click Me!"); mBuilder.setContentText("Hi, This is Android Notification Detail!");

其餘還有很多可選屬性,完整清單可查閱 NotificationCompat.Builder 官方文件。

步驟三:加上動作

這一步是選用的,但它讓通知真正變得實用——使用者點一下通知,就能直接跳進 App 中的某個 Activity 繼續處理後續工作。

動作的本質是一個 PendingIntent,裡面包著指向某個 Activity 的 Intent,再透過對應的 Builder 方法綁到通知上。最常見的是用 setContentIntent() 指定「點擊通知本文時要做什麼」。

PendingIntent 的有趣之處在於:它代表「應用程式要在稍後某個時間點執行一個動作」,即使當時你的 App 根本沒在執行也無妨。

實務上還會用 TaskStackBuilder 建立人工的回退堆疊,確保使用者從通知進入後按返回鍵時,導航行為符合預期,最終能回到 App 主畫面:

 Intent resultIntent = new Intent(this, ResultActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(ResultActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent);

步驟四:發出通知

最後呼叫 NotificationManager.notify() 把通知交給系統。別忘了先呼叫 build() 把建構器打包成 Notification 物件——這個方法會彙整所有已設定的選項並回傳新物件:

 NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // notificationID allows you to update the notification later on. mNotificationManager.notify(notificationID, mBuilder.build());

這裡的 notificationID 是個關鍵設計:只要後續用同一個 ID 再次呼叫 notify(),系統就會更新既有通知而不是新增一條。換了新 ID,才會在通知清單中多出一筆。

NotificationCompat.Builder 常用方法

這個類別讓旗標控制與常見通知布局的建立都變得容易。以下是幾個最常用到的方法:

方法說明
Notification build()彙整所有已設定的選項,回傳新的 Notification 物件
setAutoCancel(boolean autoCancel)設為 true 時,使用者點擊後通知會自動關閉
setContent(RemoteViews views)以自訂 RemoteViews 取代標準布局
setContentInfo(CharSequence info)在右側顯示附加資訊文字
setContentIntent(PendingIntent intent)指定通知被點擊時要發出的 PendingIntent
setContentText(CharSequence text)設定通知的第二行文字
setContentTitle(CharSequence title)設定通知的第一行文字
setDefaults(int defaults)設定要採用的預設通知選項
setLargeIcon(Bitmap icon)設定顯示於通知中的大圖示
setNumber(int number)在通知右側顯示數字
setOngoing(boolean ongoing)標記這是否為持續性的通知
setSmallIcon(int icon)設定通知布局中使用的小圖示
setStyle(NotificationCompat.Style style)套用更豐富的通知樣式
setTicker(CharSequence tickerText)設定通知首次抵達時顯示於狀態列的文字
setVibrate(long[] pattern)設定震動模式
setWhen(long when)設定事件發生時間,通知面板會依此排序

實作範例

以下範例示範通知的建立、更新與取消。NotificationCompat.Builder 類別自 Android 4.1 起導入。

步驟說明
1用 Android Studio 建立專案 NotificationDemo,目標 SDK 設為最新版本。
2修改 MainActivity.java,實作 startNotification()、cancelNotification() 與 updateNotification() 三個方法。
3新增 src/NotificationView.java,作為點擊通知後啟動的目標 Activity。
4把 woman.png 複製到 res/drawable-* 目錄作為通知圖示,可依解析度準備不同版本。
5修改 res/layout/activity_main.xml,以線性配置放入三個按鈕。
6新增 res/layout/notification.xml,作為新 Activity 的布局。
7在 res/values/strings.xml 定義所需常數。
8執行應用程式並驗證結果。

MainActivity.java:

 package com.example.notificationdemo; import android.os.Bundle; import android.app.Activity; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private NotificationManager mNotificationManager; private int notificationID = 100; private int numMessages = 0; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button startBtn = (Button) findViewById(R.id.start); startBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { displayNotification(); } }); Button cancelBtn = (Button) findViewById(R.id.cancel); cancelBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { cancelNotification(); } }); Button updateBtn = (Button) findViewById(R.id.update); updateBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { updateNotification(); } }); } protected void displayNotification() { Log.i("Start", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("New Message"); mBuilder.setContentText("You've received new message."); mBuilder.setTicker("New Message Alert!"); mBuilder.setSmallIcon(R.drawable.woman); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, NotificationView.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationView.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /* notificationID allows you to update the notification later on. */ mNotificationManager.notify(notificationID, mBuilder.build()); } protected void cancelNotification() { Log.i("Cancel", "notification"); mNotificationManager.cancel(notificationID); } protected void updateNotification() { Log.i("Update", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("Updated Message"); mBuilder.setContentText("You've got updated message."); mBuilder.setTicker("Updated Message Alert!"); mBuilder.setSmallIcon(R.drawable.woman); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, NotificationView.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationView.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /* Update the existing notification using same notification ID */ mNotificationManager.notify(notificationID, mBuilder.build()); } }

NotificationView.java 只是個簡單的落地頁:

 package com.example.notificationdemo; import android.os.Bundle; import android.app.Activity; public class NotificationView extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.notification); } }

activity_main.xml 放三顆按鈕:

 <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/start" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start_note"/> <Button android:id="@+id/cancel" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/cancel_note" /> <Button android:id="@+id/update" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/update_note" /> </LinearLayout>

notification.xml:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="400dp" android:text="Hi, Your Detailed notification view goes here...." /> </LinearLayout>

strings.xml:

 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">NotificationDemo</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="start_note">Start Notification</string> <string name="cancel_note">Cancel Notification</string> <string name="update_note">Update Notification</string> </resources>

AndroidManifest.xml 中要額外宣告 NotificationView,並用 parentActivityName 建立父子關係,讓返回鍵行為正確:

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.notificationdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.yiibai.notificationdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".NotificationView" android:label="Details of notification" android:parentActivityName=".MainActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity"/> </activity> </application> </manifest>

執行與觀察

執行 NotificationDemo。請確認 AVD 與環境都已設定好,模擬器畫面如下:

按下「Start Notification」,螢幕上方會先閃過一則「New Message Alert!」的提示文字,接著在左上角留下一個小圖示:

按住這個小圖示約一秒再往下拖,狀態列就會展開成完整的通知面板,顯示詳細內容:

點擊通知本身,就會啟動我們設定好的 NotificationView Activity:

從「Details of notification」返回主畫面後,可以試試「Update Notification」按鈕。它會更新既有的那則通知,右側數字加一;相對地,如果改送新的 notificationID,通知就會在清單中另行列出。而「Cancel Notification」則直接把通知移除。

大樣式通知:InboxStyle

標準通知只有兩行空間,資訊量大的時候很侷促。以下程式片段示範改用收件箱樣式的大視圖,最多可列出六行。只要修改 displayNotification() 方法即可:

 protected void displayNotification() { Log.i("Start", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setContentTitle("New Message"); mBuilder.setContentText("You've received new message."); mBuilder.setTicker("New Message Alert!"); mBuilder.setSmallIcon(R.drawable.woman); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages); /* Add Big View Specific Configuration */ NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); String[] events = new String[6]; events[0] = new String("This is first line...."); events[1] = new String("This is second line..."); events[2] = new String("This is third line..."); events[3] = new String("This is 4th line..."); events[4] = new String("This is 5th line..."); events[5] = new String("This is 6th line..."); // Sets a title for the Inbox style big view inboxStyle.setBigContentTitle("Big Title Details:"); // Moves events into the big view for (int i=0; i < events.length; i++) { inboxStyle.addLine(events[i]); } mBuilder.setStyle(inboxStyle); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, NotificationView.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationView.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /* notificationID allows you to update the notification later on. */ mNotificationManager.notify(notificationID, mBuilder.build()); }

重新執行應用程式後,展開通知就會看到多行列出內容的擴展視圖:

通知機制的設計目標很明確:在不打斷使用者的前提下,把重要訊息可靠地送達,並讓使用者能在自己選擇的時機處理。除了本文提到的 InboxStyle,Android 還提供 BigTextStyle、BigPictureStyle 等樣式;而在 Android 8.0 之後,所有通知都必須綁定到一個 notification channel,並在建立通知前先呼叫 NotificationManager.createNotificationChannel(),否則通知不會顯示——這是移植這類範例到新版 SDK 時最常踩到的坑。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved