編輯:關於 Android 開發
當 App 有事情要告訴使用者,又不適合打斷他手上的操作時,通知列就是最合適的管道。本文用最精簡的兩個按鈕——一個發通知、一個取消通知——把 Notification 的基本用法走一遍。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<Button android:id="@+id/bt_up"
android:onClick="openNotify"
android:text="open" />
<Button android:id="@+id/bt_down"
android:layout_below="@id/bt_up"
android:onClick="closeNotify"
android:text="close" />
</RelativeLayout>
在動手之前,先把三個容易混淆的類別分清楚:
Intent 是即時的,它隨所在的 Activity 一起消失。而 PendingIntent 可以視為對 Intent 的包裝:它裡面保存了當前 App 的 Context,因此外部程式(在這個例子裡是系統的通知列)可以「代替你的 App」執行這個 Intent——即使執行時你的 App 已經不在前景,甚至已被結束,也一樣能運作。它常與 AlarmManager、NotificationManager 一起出現,可以理解為「延遲或委外執行的 Intent」。
public class MainActivity extends Activity {
private NotificationManager notifyManager;
private Notification notify;
private Intent intent;
private PendingIntent pendIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
// 發送通知
public void openNotify(View v) {
notify = new Notification(R.drawable.ic_launcher, "通知", System.currentTimeMillis());
intent = new Intent(getApplicationContext(), MainActivity.class);
// requestCode 用於區分不同的 PendingIntent,後兩個參數分別是 Intent 與 flags
pendIntent = PendingIntent.getActivity(getApplicationContext(), 100, intent, 0);
notify.setLatestEventInfo(getApplicationContext(), "通知", "通知的內容", pendIntent);
notify.flags = Notification.FLAG_AUTO_CANCEL;
notifyManager.notify(100, notify);
}
// 取消通知
public void closeNotify(View v) {
pendIntent.cancel();
}
}
notify(id, notification) 的 id 是通知的身份。用同一個 id 發送,會更新原本那則通知而不是疊一個新的。這在實作「下載進度」這類需要持續更新的通知時非常好用。
FLAG_AUTO_CANCEL 讓通知可以點掉。加上這個旗標後,使用者點擊通知,系統會自動把它從通知列移除。
取消通知有兩種方式。除了 pendIntent.cancel(),也可以直接呼叫 notifyManager.cancel(id),後者更直接,不必保留 PendingIntent 的參考。
必須誠實指出:Notification 的建構方式在 Android 5.0 之後出現了 Notification.Builder,Android 8.0(API 26)更強制要求指定通知管道(NotificationChannel),而 setLatestEventInfo() 早已被移除。本文的寫法適用於早期版本,理解它的用意在於釐清 PendingIntent 的角色;實際開發時請改用 Builder 模式,並記得建立通知管道,否則在較新的系統上通知根本不會顯示。
自訂 Dialog 中的 EditText 無法彈出軟鍵盤:原因與解法
最近獨立開發的專案《全醫會》已在內測階段,很快會上架各大應用市場。之前幾個專案因為種種原因無緣上架,始終有些遺憾,所以這次心情格外好。 今天在做一個新專案,是專為律師與客
HBase、Thrift 與 C++ 用戶端開發指南
HBase、Thrift 與 C++ 用戶端開發指南 本文說明如何使用 C++ 透過 Thrift2 存取 HBase。自 HBase 0.94 起提供 Thrift2
Android 天氣 App 版面練習:RelativeLayout 與 LinearLayout 的組合
天氣 App 版面練習 這個範例以 RelativeLayout 為主體,搭配 LinearLayout 排列次要資訊,適合練習天氣首頁常見的置中與相對定位。 畫面中上
Android 內存分析工具入門:Memory Monitor、Heap Viewer 與 Allocation Tracker
Heap Viewer、Memory Monitor 與 Allocation Tracker 都是用來「視覺化」你的 App 內存使用情况的輔助工具,三者各有側重,搭配