首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android Notification 點擊跳轉失效:棄用 setLatestEventInfo 改用 NotificationCompat.Builder

     編輯:程式設計疑難解答

現象:程式碼無報錯,但點擊通知欄無法跳轉

使用已棄用的 Notification.setLatestEventInfo(),在 Android 4.1+ (API 16) 以上行為不一致,導致 PendingIntent 不觸發。

根本原因:API 過舊,缺少 Builder 模式的完整屬性設定


// ❌ 舊寫法 (API 11-15 過渡期)
Notification n = new Notification();
n.setLatestEventInfo(context, "標題", "內容", pendingIntent);
nm.notify(0, n);

現代標準寫法:NotificationCompat.Builder


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());

Android 8.0+ (API 26) 必須建立 NotificationChannel


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✅ 必填跳轉核心
NotificationChannelAPI 26+ 必填否則通知不顯示
setAutoCancel建議避免殘留通知

完整跳轉 Activity 範例


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 版本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved