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);
NotificationChannel,傳入 Builder(context, channelId)。setSmallIcon 必須設置,否則通知不顯示。androidx.core.app.NotificationCompat,而非舊 android.support.v4.app。FLAG_IMMUTABLE 或 FLAG_MUTABLE。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 模式,不僅解決棄用警告,更能統一管理通知樣式、動作、分組等高級功能。