編輯:進階開發
Toast 類別提供了最省事的方式來向使用者顯示提示訊息,但它並不持久——訊息在螢幕上閃個幾秒就消失了。對於真正重要、需要使用者記得的訊息,我們需要更長效的手段。
這就是 Notification 的用武之地。通知會以圖示形式出現在裝置頂部的通知列或狀態列中,使用者可以在方便時再回頭處理。
要看通知的細節,只要點開通知抽屜即可。在模擬器上,按住狀態列往下拖就能展開,這時看到的是一個高約 64sp 的標準視圖:
若資訊量較大,還可以把它擴展成一個更大的視圖,容納更多細節,最多可放六行。下圖就是這種擴展形式:
整個流程可以拆成四個步驟。
先用 NotificationCompat.Builder 建立一個建構器,後續所有設定都透過它進行:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
取得建構器後,就能指定各項屬性。其中有三項是必填的:
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,才會在通知清單中多出一筆。
這個類別讓旗標控制與常見通知布局的建立都變得容易。以下是幾個最常用到的方法:
| 方法 | 說明 |
|---|---|
| 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」則直接把通知移除。
標準通知只有兩行空間,資訊量大的時候很侷促。以下程式片段示範改用收件箱樣式的大視圖,最多可列出六行。只要修改 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 時最常踩到的坑。
NDK 入門專案實戰(一)
目標:利用 NDK 生成 SO 函式庫,透過 SO 函式庫進行 JNI 呼叫,在 Android sdcard 建立檔案並寫入資料。 工具:NDK 1.5 R1、Andr
市面上的Android手機,真的熱賣嗎?
Android手機的核心系統服務建立在Linux 2.6核心之上,安全性、記憶體管理、行程管理、網路協議疊與驅動模型都由此提供,而這些又統一由一個工作管理器協調,用起来既
Android ROOT權限解析:高級控制、漢化與一鍵工具的風險
ROOT權限能帶來什麼 在Android世界,ROOT權限常被視為進階玩法的門票。取得最高權限後,使用者可以存取系統目錄、移除預裝程式、更換主題、載入漢化包,也能讓部分需
Android 多任務的真相:便利的通知機制與尚未補齊的短板
Android 手機平台的強大之處不勝枚舉,這裡先談幾項基本特性。有些功能在國內難以實現,但已支援中文的語音搜尋,多少看出 Google 對中國市場的重視。 地圖與瀏覽