編輯:關於 Android 程式設計
好久沒碰 Android 的通知功能,日前把兩年前的舊專案翻出來重跑,才發現當年寫的 API 幾乎全被畫上了刪除線。於是照著 Google 官方文件重新梳理了一遍,把常用的通知寫法整理成這篇筆記,給需要的人做個參考。
以下程式碼均以官方指南為依據:
https://developer.android.com/guide/topics/ui/notifiers/notifications.html
一切的通知操作,都要先從系統服務拿到 NotificationManager 實例:
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
下面這段是通知的最小骨架,各個 setter 的用途都寫在註解裡:
public void simpleNotice(View view) { //此Builder為android.support.v4.app.NotificationCompat.Builder中的,下同。 Builder mBuilder = new Builder(this); //系統收到通知時,通知欄上面顯示的文字。 mBuilder.setTicker("天津,晴,2~15度,微風"); //顯示在通知欄上的小圖標 mBuilder.setSmallIcon(R.drawable.consult_answer); //通知標題 mBuilder.setContentTitle("天氣預報"); //通知內容 mBuilder.setContentText("天津,晴,2~15度,微風"); //設置大圖標,即通知條上左側的圖片(如果只設置了小圖標,則此處會顯示小圖標) mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.share_sina)); //顯示在小圖標左側的數字 mBuilder.setNumber(6); //設置為不可清除模式 mBuilder.setOngoing(true); //顯示通知,id必須不重復,否則新的通知會覆蓋舊的通知(利用這一特性,可以對通知進行更新) nm.notify(1, mBuilder.build()); }
這裡有個容易被忽略的細節:notify 的第一個參數是通知 id,它必須唯一。若用同一個 id 再次發送,新通知會直接覆蓋舊的——實務上正好可以拿這個特性做「通知更新」。
傳入對應的 id 即可:
nm.cancel(1);
要讓「返回鍵」的行為符合操作直覺,得靠 TaskStackBuilder 來描述頁面之間的父子關係:
//點擊通知進入一個Activity,點擊返回時進入指定頁面。 public void resultActivityBackApp(View view) { Builder mBuilder = new Builder(this); mBuilder.setTicker("通知標題2"); mBuilder.setSmallIcon(R.drawable.ic_launcher); mBuilder.setContentTitle("通知標題2"); mBuilder.setContentText("點擊通知進入一個Activity,點擊返回時進入指定頁面。"); //設置點擊一次後消失(如果沒有點擊事件,則該方法無效。) mBuilder.setAutoCancel(true); //點擊通知之後需要跳轉的頁面 Intent resultIntent = new Intent(this, ResultActivityBackApp.class); //使用TaskStackBuilder為“通知頁面”設置返回關系 TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); //為點擊通知後打開的頁面設定 返回 頁面。(在manifest中指定) stackBuilder.addParentStack(ResultActivityBackApp.class); stackBuilder.addNextIntent(resultIntent); PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pIntent); // mId allows you to update the notification later on. nm.notify(2, mBuilder.build()); }
同時要在 manifest 裡為這個 Activity 宣告父 Activity:
<activity android:name=".ResultActivityBackApp" android:parentActivityName=".MainActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity>
補充一句:parentActivityName 是 API 16 才有的屬性,meta-data 那段則是為了向下相容。所以大多數專案裡這兩處都得寫上。
如果希望按返回直接回到 launcher,那就不需要 TaskStackBuilder,改用 FLAG_ACTIVITY_NEW_TASK 的 Intent 就好:
//點擊通知進入一個Activity,點擊返回時回到桌面 public void resultActivityBackHome(View view) { Builder mBuilder = new Builder(this); mBuilder.setTicker("通知標題3"); mBuilder.setSmallIcon(R.drawable.ic_launcher); mBuilder.setContentTitle("通知標題3"); mBuilder.setContentText("點擊通知進入一個Activity,點擊返回時回到桌面"); //設置點擊一次後消失(如果沒有點擊事件,則該方法無效。) mBuilder.setAutoCancel(true); Intent notifyIntent = new Intent(this, ResultActivityBackHome.class); notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pIntent); nm.notify(3, mBuilder.build()); }
下載、上傳這類耗時任務很適合用它。關鍵是同一個 id 反覆 notify,讓進度原地刷新:
public void progressNotice(View view) { final Builder mBuilder = new Builder(this); mBuilder.setTicker("通知標題4"); mBuilder.setContentTitle("Picture Download") .setContentText("Download in progress") .setSmallIcon(R.drawable.ic_launcher); // Start a lengthy operation in a background thread new Thread(new Runnable() { @Override public void run() { int progress; for (progress = 0; progress <= 100; progress++) { // Sets the progress indicator to a max value, the current completion percentage, // and "determinate" state mBuilder.setProgress(100, progress, false); //不明確進度的進度條 // mBuilder.setProgress(0, 0, true); nm.notify(4, mBuilder.build()); // 模擬延時 try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } // When the loop is finished, updates the notification mBuilder.setContentText("Download complete"); // Removes the progress bar mBuilder.setProgress(0, 0, false); nm.notify(4, mBuilder.build()); } } ).start(); }
把通知往下滑,就能展開顯示更多行內容,InboxStyle 是最常用的一種樣式:
public void expandLayoutNotice(View view) { Builder mBuilder = new Builder(this); mBuilder.setTicker("通知標題5"); mBuilder.setSmallIcon(R.drawable.ic_launcher); mBuilder.setContentTitle("通知標題5"); mBuilder.setContentText("按住通知下拉可顯示擴展布局"); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); String[] events = new String[]{"Beijing", "Tianjin", "Shanghai", "Guangzhou"}; // 設置擴展布局的標題 inboxStyle.setBigContentTitle("Event tracker details:"); for (String s : events) { inboxStyle.addLine(s); } mBuilder.setStyle(inboxStyle); nm.notify(5, mBuilder.build()); }
官方文件並不鼓勵這麼做:RemoteViews 要兼顧各種螢幕尺寸與系統版本,成本遠高於收益。而且通知欄的定位本來就是「一眼看完的精簡資訊」,預設樣式對絕大多數 App 已經夠用。
//自定義布局的通知 public void customLayoutNotice(View view) { Builder mBuilder = new Builder(this); mBuilder.setTicker("通知標題6"); mBuilder.setTicker("通知標題6"); mBuilder.setSmallIcon(R.drawable.ic_launcher); RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_layout_notice); mBuilder.setContent(remoteViews); //為RemoteViews上的按鈕設置文字 remoteViews.setCharSequence(R.id.custom_layout_button1, "setText", "Button1"); remoteViews.setCharSequence(R.id.custom_layout_button2, "setText", "Button2"); //為RemoteViews上的按鈕設置點擊事件 Intent intent1 = new Intent(this, CustomLayoutResultActivity.class); intent1.putExtra("content", "From button1 click!"); PendingIntent pIntentButton1 = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.custom_layout_button1, pIntentButton1); Intent intent2 = new Intent(this, CustomLayoutResultActivity.class); intent2.putExtra("content", "From button2 click!"); PendingIntent pIntentButton2 = PendingIntent.getActivity(this, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.custom_layout_button2, pIntentButton2); nm.notify(6, mBuilder.build()); }
以上就是通知欄常見的幾種用法。真正上專案時建議以 NotificationCompat.Builder 為基準,並記得照顧不同 Android 版本在通知渠道(NotificationChannel)上的差異。
動手做一個 Android 藍牙電子鐘小專案
Android 藍牙電子鐘實作教學 本篇文章將帶你打造一個能透過藍牙與多功能數位電子鐘溝通的小應用。透過手機端的藍牙連結,我們可以更新電子鐘的時間、設定監控時段、調整鬧鐘
Android 學習筆記:Fragment 生命週期與回調順序
Fragment 作為 Android 中常用的界面組件,擁有自己的生命週期。理解 Fragment 的回調順序,有助於開發者在合適的時機保存狀態、恢復數據以及釋放資源。
GridView 實作九宮格首頁:拆解人人網 Android 客戶端的版面設計
早期的人人網 Android 客戶端首頁給人印象很深:一塊整齊的九宮格,每格上方圖示、下方文字,簡潔又有秩序。在當時多數應用仍把功能一條條堆在列表裡的背景下,這種配置顯得
Android 系統服務之 AlarmManager 鬧鐘服務詳解
本節引言 本文介紹 Android 系統服務中的 AlarmManager(鬧鐘服務)。除了開發手機鬧鐘,它更常被當作一個全域的定時器,通常與 Service 搭配,在指