使用已棄用的 Notification.setLatestEventInfo(),在 Android 4.1+ (API 16) 以上行為不一致,導致 PendingIntent 不觸發。
// ❌ 舊寫法 (API 11-15 過渡期)
Notification n = new Notification();
n.setLatestEventInfo(context, "標題", "內容", pendingIntent);
nm.notify(0, n);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification) // 必須
.setContentTitle("標題")
.setContentText("點擊查看")
.setContentIntent(pendingIntent)
.setAutoCancel(true) // 點擊後自動取消
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat.from(this).notify(notifyId, builder.build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID, "頻道名稱", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("頻道描述");
NotificationManagerCompat.from(this).createNotificationChannel(channel);
}
| 項目 | 必要性 | 說明 |
|---|---|---|
setSmallIcon | ✅ 必填 | 缺少會崩潰或不顯示 |
setContentIntent | ✅ 必填 | 跳轉核心 |
NotificationChannel | API 26+ 必填 | 否則通知不顯示 |
setAutoCancel | 建議 | 避免殘留通知 |
Intent intent = new Intent(this, TargetActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("新訊息")
.setContentText("點擊進入")
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat.from(this).notify(1, builder.build());
結論:**棄用 setLatestEventInfo,全面遷移到 NotificationCompat.Builder + NotificationChannel**,相容所有 Android 版本。