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

Android Studio 提示 Notification 構造函數已棄用:遷移至 NotificationCompat.Builder 完整步驟

     編輯:程式設計疑難解答

Android Studio 提示 Notification 構造函數已棄用:遷移至 NotificationCompat.Builder 完整步驟

Android O (API 26) 後,new Notification(...) 構造函數標記 @Deprecated,強制要求使用 NotificationCompat.Builder 構建通知,以保證跨版本兼容性。

舊代碼(已棄用)

Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, title, content, pendingIntent);

新代碼(標準寫法)

// 依賴:implementation "androidx.core:core:1.12.0"
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle(title)
        .setContentText(content)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);

Notification notification = builder.build();
notificationManager.notify(NOTIFICATION_ID, notification);

關鍵遷移點

  1. 通知渠道:API 26+ 必須創建 NotificationChannel,傳入 Builder(context, channelId)。
  2. 圖標:setSmallIcon 必須設置,否則通知不顯示。
  3. 兼容包:使用 androidx.core.app.NotificationCompat,而非舊 android.support.v4.app。
  4. PendingIntent 旗標:Android 12+ 需顯式指定 FLAG_IMMUTABLE 或 FLAG_MUTABLE。

完整創建渠道代碼 (Application/Service 中)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
        CHANNEL_ID, "頻道名稱", NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("頻道描述");
    NotificationManager manager = getSystemService(NotificationManager.class);
    manager.createNotificationChannel(channel);
}

遷移至 Builder 模式,不僅解決棄用警告,更能統一管理通知樣式、動作、分組等高級功能。

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