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

Android 通知欄無法顯示:權限、通道與常見誤區排查

     編輯:程式設計疑難解答

現象

程式碼邏輯正確,NotificationManager.notify() 呼叫無誤,但狀態列完全不出現通知。

排查清單(依優先序)

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

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(
        "channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Description");
    NotificationManager manager = getSystemService(NotificationManager.class);
    manager.createNotificationChannel(channel);
}
// 建構通知時指定相同 channelId
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id");

缺少 Channel 會導致通知靜默丟棄,無任何錯誤訊息。

2. 應用通知權限被使用者關閉

  • 設定 → 應用程式 → 該 App → 通知 → 確認「允許通知」開啟。
  • 代碼可引導使用者開啟:startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName()));

3. 圖示資源問題

  • setSmallIcon() 必須設定,**且圖示必須為純白透明 PNG**(Android 規範),否則可能顯示為白方塊或完全不顯示。
  • 避免使用 mipmap/ic_launcher 等彩色圖示作為 SmallIcon。

4. 通知 ID 衝突與覆蓋

  • notify(id, notification) 若同一 ID 連續呼叫,後者會覆蓋前者。測試時改用遞增 ID 或 System.currentTimeMillis()。

5. 前台服務需求

  • Android 9+ 若在前台服務中發送通知,服務必須先呼叫 startForeground() 並提供通知,否則系統可能限制。

6. Doze 模式 / 省電優化

  • 若裝置進入 Doze,高優先級 FCM 訊息可喚醒,但本地 NotificationManager 可能延遲。測試時關閉電池優化或使用 setPriority(NotificationCompat.PRIORITY_HIGH)。

7. 程式碼邏輯錯誤(參考原詢代碼)

  • startActivity(intent) 在 notify() **之前**呼叫會啟動 Activity 而非顯示通知。移除該行或改用 PendingIntent 包裝。
  • 確認 PendingIntent.getActivity(..., PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE) (API 23+ 需 FLAG_IMMUTABLE)。

最小可行測試代碼

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "test_channel")
    .setSmallIcon(R.drawable.ic_notification) // 純白圖示
    .setContentTitle("測試標題")
    .setContentText("測試內容")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setAutoCancel(true);

NotificationManagerCompat.from(this).notify(1, builder.build());

總結

90% 的「通知不顯示」源於 **缺少 NotificationChannel**、**圖示不合規** 或 **使用者關閉權限**。按上述清單逐項驗證即可定位。

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