モケラ

Tech Sheets

mokelab

Androidで通知を表示する

最終更新日:2017-09-03

Androidで通知を表示するには、`Notification`オブジェクトを作ります。

Android OSのバージョンに強く依存するので、サポートライブラリにある`NotificationCompat`の使用をおすすめします。

String channelId = "news";
String title = "運営からのお知らせ";

NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext(), channelId);
builder.setContentText(title);
builder.setSmallIcon(R.drawable.ic_notification_24dp);

まず、通知を組み立てるための`Builder`を作ります。第2引数にはチャネルIDを指定します。次に、通知で表示するタイトルやアイコンを指定します。アイコンは24x24dpの白と透明色だけで構成したものを指定しましょう。

組み立てが完了したら、`build()`で`Notification`オブジェクトを作成し、`notify()`で通知を行います。

int notificationId = 1;

NotificationManager manager = getContext().getSystemService(NotificationManager.class);
manager.notify(notificationId, builder.build());

一覧に戻る