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

Android Notification.setLatestEventInfo 參數不匹配錯誤的根因與遷移指南

     編輯:程式設計疑難解答

錯誤現象

代碼 notification.setLatestEventInfo(MainActivity.this, getString(R.string.app_name), "我是string", contextIntent); 編譯報錯「參數不匹配」,提示實際參數類型為 (MainActivity, String, String, Intent)。

根因解析

  1. API 已棄用:setLatestEventInfo 自 API Level 11 (Android 3.0) 起標記 @Deprecated,且在高版本 SDK 中可能被移除或簽名變更;
  2. 最後一個參數類型錯誤:官方簽名為 PendingIntent contentIntent,傳入的是 Intent 對象,導致類型不匹配。

正確構建 PendingIntent

Intent intent = new Intent(this, TargetActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
    this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

現代化寫法:NotificationCompat.Builder(推薦)

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle(getString(R.string.app_name))
    .setContentText("我是string")
    .setContentIntent(contentIntent)
    .setAutoCancel(true)
    .setPriority(NotificationCompat.PRIORITY_DEFAULT);

NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, 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);
    NotificationManagerCompat.from(this).createNotificationChannel(channel);
}

遷移檢查清單

  • 替換所有 Notification 直接實例化為 NotificationCompat.Builder;
  • 統一管理 CHANNEL_ID 常量;
  • 針對 Android 12+ (API 31) 添加 FLAG_IMMUTABLE 或 FLAG_MUTABLE;
  • 使用 NotificationManagerCompat 兼容不同版本行為。

總結

棄用 API 不再維護,請全面遷移至 NotificationCompat.Builder 體系,並按版本處理 Channel 與 PendingIntent 標誌位,確保跨版本穩定性。

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