代碼 notification.setLatestEventInfo(MainActivity.this, getString(R.string.app_name), "我是string", contextIntent); 編譯報錯「參數不匹配」,提示實際參數類型為 (MainActivity, String, String, Intent)。
setLatestEventInfo 自 API Level 11 (Android 3.0) 起標記 @Deprecated,且在高版本 SDK 中可能被移除或簽名變更;PendingIntent contentIntent,傳入的是 Intent 對象,導致類型不匹配。Intent intent = new Intent(this, TargetActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(
this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
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());
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 常量;FLAG_IMMUTABLE 或 FLAG_MUTABLE;NotificationManagerCompat 兼容不同版本行為。棄用 API 不再維護,請全面遷移至 NotificationCompat.Builder 體系,並按版本處理 Channel 與 PendingIntent 標誌位,確保跨版本穩定性。