編輯:關於 Android 程式設計
在 Android 中發送多個通知(Notification)時,最容易踩的坑就是——PendingIntent 的請求碼(ID)至關重要。如果每個通知的 PendingIntent 使用了相同的 ID,系統會認為它們指向同一個意圖,導致通知被相互覆蓋,無法正常分開顯示。因此,為每個通知分配唯一的 ID,是實現多通知並存的核心。
下面的示例基於 Cordova 插件場景,示範如何發送多個可區分的通知:
public void addNotification(JSONArray args, CallbackContext callbackContext) throws JSONException {
// NOTIFICATION_ID 至關重要,這裡隨機生成一個,確保每條通知唯一
NOTIFICATION_ID = (int) (Math.random() * 10000);
try {
nm = (NotificationManager) cordova.getActivity()
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(cx, cordova.getActivity().getClass());
intent.putExtra("clickAction", args.getString(4));
String clickActionParams = args.getJSONObject(5).toString();
intent.putExtra("clickActionParams", clickActionParams);
PendingIntent pIntent = PendingIntent.getActivity(
cx, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int version = android.os.Build.VERSION.SDK_INT;
Notification notify;
// 版本號大於 15 採用 Notification.Builder,否則用舊方法,避免部分機型問題
if (version > 15) {
notify = new Notification.Builder(cx)
.setAutoCancel(true) // 點擊後自動消失
.setTicker(args.getString(0)) // 狀態欄提示文字
.setSmallIcon(R.drawable.icon) // 通知圖標
.setContentTitle(args.getString(0)) // 通知標題
.setContentText(args.getString(1) + NOTIFICATION_ID) // 通知內容
.setWhen(System.currentTimeMillis()) // 通知時間
.setContentIntent(pIntent).build(); // 點擊後啟動的 Intent
} else {
notify = new Notification(R.drawable.icon, args.getString(0),
System.currentTimeMillis());
notify.setLatestEventInfo(cx, args.getString(0), args.getString(1), pIntent);
}
// 發送通知
nm.notify(NOTIFICATION_ID, notify);
// 通知顯示一段時間後自動清除
if (args.getBoolean(2)) {
disappearTime = args.getLong(3);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
nm.cancel(NOTIFICATION_ID);
}
}, disappearTime);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
這段程式碼的關鍵有兩點:其一,NOTIFICATION_ID 唯一,且 PendingIntent 使用相同的 ID 保持一致;其二,根據系統版本選擇不同的通知構建方式,兼顧了新舊機型的相容性。掌握這兩點,你就能從容地在一個應用中推送並管理多條互不干擾的通知。
Android 二維碼開源專案 ZXing 的編譯與踩坑記錄
ZXing 是一個開放原始碼、以 Java 實作的多格式 1D/2D 條碼圖像處理庫,並有對應其他語言的移植版本。它能呼叫手機內建相機完成條碼掃描與解碼,同時支援條碼的編
Android 官方 MVP 架構解析:從 todo-mvp 看職責分離
MVP 是 Android 開發中常見的架構模式之一,全名為 Model View Presenter。它從 MVC 演進而來,主要目的在於降低 View 與業務邏輯之間
Android Studio 報錯 9-patch image malformed 的原因與修法
在 Android Studio 中處理 .9.png 時,常會看到這則錯誤: ERROR: 9-patch image icon_item_bottom_line.9.
Android 開發實作:解析 XML 並打造省/市/區三級聯動
本實例主要示範如何使用 XmlPullParser 解析 XML 文件中的省、市、區資料,再把資料綁定到 Spinner 上,實現三級聯動的效果。關於 XmlPullPa