0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NotificationCompat.Builderの書き方2パターン

Posted at

はじめに

NotificationCombat.Builderの書き方が2種類あって、違いについて気になったのでまとめた

Java
1. Notification notification = new NotificationCompat.Builder
2. NotificationCompat.Builder builder = new NotificationCompat.Builder

✅ 結論

用途 推奨される書き方
通知のみ(ボタンなし) 1. チェーン式で1行完結
アクションボタンを付けたい場合 2. Builderを変数にして操作

🧪 シンプルな通知(1行完結)

Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("新着エピソード")
    .setContentText("○○に新しいエピソードがあります")
    .build();
  • ✅ 短くて読みやすい
  • ❌ アクション追加などの柔軟な処理には不向き

🧪 アクションボタン付き通知

NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("新着エピソード")
    .setContentText("再生またはダウンロードできます");

// アクション追加
builder.addAction(R.drawable.ic_play, "再生", playPendingIntent);
builder.addAction(R.drawable.ic_download, "DL", downloadPendingIntent);

Notification notification = builder.build();
  • ✅ アクション追加・条件分岐がしやすい
  • ❌ コードは少し長め

✅ まとめ

  • 通知だけなら 1行完結でOK
  • アクションボタン付き通知は Builder変数を使うべし

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?