編輯:關於 Android 程式設計
Notification 是顯示在手機狀態列的通知,代表一種具有全域效果的通知訊息,程式通常透過 NotificationManager 服務來發送。從 Android 3.0 起,新增了 Notification.Builder 類別,可以更輕鬆地建立 Notification 物件。
builder.setAutoCancel(); 設定點擊通知後,狀態列自動刪除通知。
builder.setSmallIcon(R.drawable.alert); 設定通知小圖示。
builder.setLargeIcon(R.drawable.alert2); 設定通知大圖示。
builder.setContentTitle("標題"); 設定通知標題。
builder.setContentText("文本"); 設定通知內容。
builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE); 設定通知的音樂、震動、LED 等。
builder.setSound(); 設定通知的音樂。
builder.setTick(); 設定通知在狀態列的提示文字。
builder.setContentIntent(); 設定點擊通知後要啟動的程式元件對應的 PendingIntent。
1、呼叫 getSystemService(NOTIFICATION_SERVICE) 取得系統的 NotificationManager 服務,這是一個重要的系統服務,應用程式可透過它向系統發送全域通知;
2、建立 Notification.Builder 物件;
3、設定 Notification.Builder 的各種屬性;
4、透過 NotificationManager 的 notify() 方法發送 Notification。
核心程式碼如下:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); builder = new Notification.Builder(this); builder.setAutoCancel(true); builder.setSmallIcon(R.drawable.alert); builder.setContentTitle("標題"); builder.setContentText("文本"); builder.setDefaults(Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE);
Intent intent = new Intent(this, SecondActivity.class); PendingIntent pIntent = PendingIntent.getActivity(this, 1, intent,PendingIntent.FLAG_ONE_SHOT); builder.setContentIntent(pIntent); manager.notify(0, builder.build());
1、PendingIntent 字面意義是「等待的、懸而未決的 Intent」;
2、取得一個 PendingIntent 物件,使用方法類別的靜態方法 getActivity(Context, int, Intent, int);
3、PendingIntent 是一種特殊的 Intent。主要差別在於 Intent 是立刻執行,而 PendingIntent 的執行不是立刻,而是當條件滿足後才發送意圖,而且 PendingIntent 可以取消;
4、PendingIntent 執行的操作,實質上是傳入參數的 Intent 的操作,使用它的目的在於:它所包含的 Intent 操作的執行需要滿足某些條件;
5、主要使用的地方與例子:通知 Notification 的發送、簡訊 SmsManager 的發送,以及警報器 AlarmManager 的執行等。
設定 notification 的點擊跳轉:
NotificationCompat.Builder builder = new NotificationCompat.Builder( MainActivity.this); builder.setContentText("344444444444"); builder.setContentTitle("33333333333"); builder.setSmallIcon(R.drawable.ic_launcher); Intent intent = new Intent(MainActivity.this, ScondActivity.class); PendingIntent intent2 = PendingIntent.getActivity( MainActivity.this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT); builder.setContentIntent(intent2); NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(1, builder.build());
在狀態列顯示通知的完整範例:
/** * 在狀態欄顯示通知 */ private void showNotification(){ // 創建一個NotificationManager的引用 NotificationManager notificationManager = (NotificationManager) this.getSystemService(android.content.Context.NOTIFICATION_SERVICE); // 定義Notification的各種屬性 Notification notification =new Notification(R.drawable.icon, "督導系統", System.currentTimeMillis()); //FLAG_AUTO_CANCEL 該通知能被狀態欄的清除按鈕給清除掉 //FLAG_NO_CLEAR 該通知不能被狀態欄的清除按鈕給清除掉 //FLAG_ONGOING_EVENT 通知放置在正在運行 //FLAG_INSISTENT 是否一直進行,比如音樂一直播放,知道用戶響應 notification.flags |= Notification.FLAG_ONGOING_EVENT; // 將此通知放到通知欄的"Ongoing"即"正在運行"組中 notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在點擊了通知欄中的"清除通知"後,此通知不清除,經常與FLAG_ONGOING_EVENT一起使用 notification.flags |= Notification.FLAG_SHOW_LIGHTS; //DEFAULT_ALL 使用所有默認值,比如聲音,震動,閃屏等等 //DEFAULT_LIGHTS 使用默認閃光提示 //DEFAULT_SOUNDS 使用默認提示聲音 //DEFAULT_VIBRATE 使用默認手機震動,需加上 權限 notification.defaults = Notification.DEFAULT_LIGHTS; //疊加效果常量 //notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND; notification.ledARGB = Color.BLUE; notification.ledOnMS =5000; //閃光時間,毫秒 // 設置通知的事件消息 CharSequence contentTitle ="督導系統標題"; // 通知欄標題 CharSequence contentText ="督導系統內容"; // 通知欄內容 Intent notificationIntent =new Intent(MainActivity.this, MainActivity.class); // 點擊該通知後要跳轉的Activity PendingIntent contentItent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, contentTitle, contentText, contentItent); // 把Notification傳遞給NotificationManager notificationManager.notify(0, notification); } //刪除通知 private void clearNotification(){ // 啟動後刪除之前我們定義的通知 NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); notificationManager.cancel(0); }
根據 Activity 的生命週期,當 Activity 不顯示時(例如按下 home 鍵)會執行 onStop 函數,所以可以在 onStop 中把 notification 放進通知欄,再次顯示時再把它從通知欄移除;或者讓程式運行期間一直顯示通知欄圖示。
常用常量:
DEFAULT_ALL 使用所有默認值,比如聲音、震動、閃屏等等。
DEFAULT_LIGHTS 使用默認閃光提示。
DEFAULT_SOUNDS 使用默認提示聲音。
DEFAULT_VIBRATE 使用默認手機震動。
說明:加入手機震動,一定要在 manifest.xml 中加入權限 <uses-permission android:name="android.permission.VIBRATE" />。以上效果常量可以疊加,例如 notification.defaults = DEFAULT_SOUND|DEFAULT_VIBRATE; 或 notification.defaults |= DEFAULT_SOUND(震動效果最好在真機上測試,模擬器上看不到)。
設定 flag 位:
FLAG_AUTO_CANCEL 該通知能被狀態列的清除按鈕給清除掉。
FLAG_NO_CLEAR 該通知不能被狀態列的清除按鈕給清除掉。
FLAG_ONGOING_EVENT 通知放置在「正在運行」。
FLAG_INSISTENT 是否一直進行,比如音樂一直播放,直到用戶響應。
常用欄位:contentIntent(設定 PendingIntent,點擊時發送)、defaults(新增默認效果)、flags(設定 flag 位)、icon(設定圖示)、sound(設定聲音)、tickerText(顯示在狀態列的文字)、when(發送此通知的時間戳)。
NotificationManager 常用方法:
public void cancelAll() 移除所有通知(僅針對當前 Context 下的 Notification)。
public void cancel(int id) 移除標記為 id 的通知。
public void notify(String tag, int id, Notification notification) 將通知加入狀態列,標籤為 tag,標記為 id。
public void notify(int id, Notification notification) 將通知加入狀態列,標記為 id。
通知是你可以顯示在使用者應用程式介面之外的一種訊息。當你要求系統發出通知時,它會先以圖示形式出現在通知區域;使用者打開通知抽屜即可查看通知詳情。通知區域與通知抽屜都是系統控制的區域,使用者可隨時查看。

圖 1. 通知區域中的通知。

圖 2. 通知抽屜中的通知。
通知抽屜中的通知可以呈現兩種視覺樣式,取決於版本與抽屜狀態:
Normal view:通知抽屜中的標準樣式。
Big view:當通知展開時顯示的較大樣式,屬於 Android 4.1 起提供的展開式通知功能。
Normal view 的通知顯示於最高 64 dp 的區域中。即使你用 big view 樣式建立通知,在展開之前仍會以 normal view 呈現。

圖 3. Normal view 通知。
插圖中的各元素包含:內容標題、大圖示、內容文字、內容資訊、小圖示,以及通知發出的時間(可用 setWhen() 明確設定,若未設定則默認為系統收到通知的時間)。
Big view 只在通知展開時出現,也就是當通知位於通知抽屜頂端,或使用者用手勢展開通知時。展開式通知從 Android 4.1 開始提供。

圖 4. Big view 通知。
big view 與 normal view 共享大部分視覺元件,唯一差別是第 7 項「詳情區域」。可用的樣式包括:
Big picture style:詳情區域包含最高 256 dp 的點陣圖。
Big text style:在詳情區域顯示一大段文字。
Inbox style:在詳情區域顯示多行文字。
此外,所有 big view 樣式都還具備 normal view 沒有的選項:Big content title(可覆寫展開檢視中的標題)與 Summary text(可在詳情區域下方新增一行文字)。
你在 NotificationCompat.Builder 物件中指定通知的 UI 資訊與動作,呼叫 NotificationCompat.Builder.build() 建立通知本身,再把 Notification 物件透過 NotificationManager.notify() 傳給系統發出。
一個 Notification 物件必須包含:小圖示(setSmallIcon())、標題(setContentTitle())、詳情文字(setContentText())。
雖然是選用,但你應該至少為通知加入一個動作,讓使用者能直接從通知跳到應用程式中的某個 Activity。一個通知可以提供多個動作,你應始終定義使用者點擊通知時觸發的動作,通常會開啟一個 Activity;此外還可加入執行附加動作的按鈕(此功能從 Android 4.1 起提供)。通知中的動作本質上由一個包含 Intent 的 PendingIntent 定義,若要將它與手勢關聯,可呼叫 setContentIntent()。
以下程式碼示範一個簡單通知,並用 TaskStackBuilder 建立動作的 PendingIntent,以保留返回時的正常導航行為:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(mId, mBuilder.build());
先以 normal view 選項建立 NotificationCompat.Builder,再呼叫 Builder.setStyle() 並傳入 big view 樣式物件即可。以下示範改用 Inbox 樣式:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Event tracker")
.setContentText("Events received")
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
String[] events = new String[6];
inboxStyle.setBigContentTitle("Event tracker details:");
...
for (int i=0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}
mBuilder.setStyle(inBoxStyle);
...
並非所有通知功能在各版本都可用,即使設定方法存在於支援庫的 NotificationCompat.Builder 中。例如依賴展開式通知的動作按鈕,只在 Android 4.1 以上出現。為確保最佳相容性,請以 NotificationCompat 及其子類別建立通知,並遵循:先在所有版本都提供完整功能(透過某個 Activity 實作),讓使用者點擊通知時能進入該 Activity,最後再加入展開式通知的進階功能。
當你需要為同一類型事件多次發出通知時,應避免每次都建立全新的通知,而是考慮更新先前的通知。例如 Gmail 會以增加未讀數量、並附加每封信摘要的方式更新通知,這稱為通知的「堆疊」(stacking)。
要讓通知可更新,發出時以 notify(ID, notification) 指定通知 ID;之後欲更新時,用相同的 ID 再次發出即可。若先前通知仍顯示,系統會更新它;若已被關閉,則會建立新通知。
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
...

圖 5. 更新後顯示在通知抽屜中的通知。
通知會持續顯示,直到下列情況之一發生:
從通知啟動 Activity 時,必須保留使用者預期的導航體驗:按 Back 應沿著應用程式的正常流程回到主畫面,按 Recents 應把該 Activity 視為獨立 task。做法是在全新的 task 中啟動 Activity,如何設定 PendingIntent 取決於 Activity 的性質,分為兩類:
Regular activity:啟動的是應用程式正常流程中的 Activity。此時應讓 PendingIntent 啟動一個全新 task,並提供能重現正常 Back 行為的回退堆疊。Gmail 就是範例:點擊單封信通知會看到該封信,按 Back 會依序回到收件匣再到主畫面,無論你點擊通知時原本在哪個應用程式。
Special activity:使用者只有在從通知啟動時才會看到這個 Activity,某種意義上它延伸了通知本身。此時讓 PendingIntent 在全新 task 中啟動即可,不需要建立回退堆疊,按 Back 仍會回到主畫面。
步驟:先在 manifest 定義 Activity 的階層(對 Android 4.0.3 以前用 <meta-data> 指定 android.support.PARENT_ACTIVITY;對 4.1 以上用 android:parentActivityName 屬性),再建立回退堆疊:
Intent resultIntent = new Intent(this, ResultActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(ResultActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(id, builder.build());
特殊 Activity 不需要回退堆疊,因此不必在 manifest 定義階層,也不必呼叫 addParentStack()。改用 manifest 設定 task 選項,再以 getActivity() 建立 PendingIntent:在 <activity> 元素中加入 android:taskAffinity=""、android:excludeFromRecents="true" 等屬性,然後:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this); Intent notifyIntent = new Intent(new ComponentName(this, ResultActivity.class)); notifyIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK); PendingIntent notifyIntent = PendingIntent.getActivity( this, 0, notifyIntent PendingIntent.FLAG_UPDATE_CURRENT ); builder.setContentIntent(notifyIntent); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(id, builder.build());
通知可包含動畫進度指示器,用來顯示進行中操作的狀態。若能估計操作所需時間與完成比例,使用「確定性」形式(進度條);若無法估計,則使用「不確定性」形式(活動指示器)。從 Android 4.0 起可呼叫 setProgress() 使用進度指示器。
呼叫 setProgress(max, progress, false) 加入進度條並發出通知,隨著操作推進遞增 progress,結束時 progress 等於 max。完成後可呼叫 setProgress(0, 0, false) 移除進度條,記得同步更新通知文字。
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Download")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.ic_notification);
new Thread(
new Runnable() {
@Override
public void run() {
int incr;
for (incr = 0; incr <= 100; incr+=5) {
mBuilder.setProgress(100, incr, false);
mNotifyManager.notify(0, mBuilder.build());
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
Log.d(TAG, "sleep failure");
}
}
mBuilder.setContentText("Download complete")
.setProgress(0,0,false);
mNotifyManager.notify(ID, mBuilder.build());
}
}
).start();

圖 6. 操作過程中與結束後的進度條。
呼叫 setProgress(0, 0, true) 即可顯示不確定性活動指示器,動畫會持續直到你修改通知。操作結束後,呼叫 setProgress(0, 0, false) 並更新通知以移除指示器,否則動畫會一直運行。
mBuilder.setProgress(0, 0, true); mNotifyManager.notify(0, mBuilder.build());

圖 7. 持續進行的活動指示器。
通知框架允許你透過 RemoteViews 物件定義自訂通知布局,其外觀由一個在 XML 布局檔中定義的 RemoteViews 決定。自訂布局通知類似於一般通知,但基於 RemoteViews。可用的高度取決於檢視:normal view 限制為 64 dp,展開檢視限制為 256 dp。定義步驟:先建立一個 inflate XML 布局檔的 RemoteViews 物件,再改用 setContent() 而非 setContentTitle(),並用 RemoteViews 的方法設定子檢視的值。
注意:使用自訂布局時,務必確保它在不同的螢幕方向與解析度下都能正常顯示,因為通知抽屜空間非常受限,不要讓布局過於複雜,並在各種配置下測試。另外,自訂通知的文字應一律使用樣式資源,因為通知背景顏色在不同裝置與版本間可能不同,使用樣式資源能確保文字在背景上清晰可見。
Android 入門:TableLayout 三個關鍵欄位屬性詳解(上)
TableLayout 與 TableRow 是一組搭配使用的佈局:TableLayout 置底,TableRow 疊在它上面,而 Button、TextView 等控件
Android 推送入門:百度雲推送快速上手
現在幾乎每個 App 都具備推送功能。本文記錄使用百度雲推送的入門過程,官方文件與 Demo 都相當完善,跟著操作即可快速串接。目標是以百度雲推送為基礎,打造一個即時通訊
自定義 View 仿 QQ 等級:成長天數進度控件
自定義 View 這塊持續看了一週多,每天更新一篇,慢慢摸到一些手感,對「怎麼算」這件事也有了更深的認識。今天在手機上看到一個成長天數的進度控件,覺得有趣,就自己動手做了
更省事也更完整的 Material Design 狀態列方案彙整
從實際需求出發,用盡可能簡短的方式實行了七種常見的 MD 狀態列型態。核心關鍵其實只有一個:fitsSystemWindows 該加在哪一層。 零、使用前提 Theme