通知の実装について
プッシュ通知の種類
プッシュ通知には、ローカル通知とプッシュ通知の2種類がある。
ローカル通知はアプリ起動中に何らかのイベントによりプッシュ通知が起きる。
リモート通知はfirebaseで通知を行う旨を受け、firebase自身がandroidに通知を送る。 例えばサーバーから信号がfirebaseに送られて、firebaseがデバイスに通知する方法がある。その他の方法としてfirebase内のプロジェクトの管理コンソールからメッセージを作成し、firebaseがデバイスに通知するのもある。
リモートにおけるプッシュ通知はAndroid リモート通知機能について - diadia
この記事の内容
この記事では、ローカル通知について記述する。
通知の概要 | Android デベロッパー | Android Developers
Androidドキュメントのガイドにおける通知の項目はすべてローカル通知について記述してあるように思われる。
したがってリモート通知については、firebaseのドキュメントを読まなければならない。
参考
Notificationを勉強し直す | Simple is Best
通知の概要 | Android デベロッパー | Android Developers
OreoでNotificationを表示させる方法 - Qiita
Androidで表示できる通知まとめ | Developers.IO
Firebase Admin SDKを使ったPush通知 - Qiita
ローカル通知機能の実装方法
最初にどうなれば通知機能を実装できるのか逆算して解説する。最後にサンプルコードを表示する。 1. 通知IDの設定 1. 通知メッセージをクリックしたら起動するPendingIntentの設定 1.
通知を表示する
通知を表示するには、NotificationManagerCompat.notify()を実行する。引数は通知の一意の ID とNotificationCompat.Builder.build() の結果である。 このメソッドの実行は作成した通知を通知させるのに使われる。
NotificationManagerCompat | Android デベロッパー | Android Developers
with(NotificationManagerCompat.from(this)) { // notificationId is a unique int for each notification that you must define notify(notificationId, builder.build()) } //または notificationManager.notify(notificationId, builder.build()) //builder.build()はNotificationオブジェクトである。
通知のコンテンツを設定(作成)する
NotificationCompat.Builderクラスを使って通知のコンテンツ内容を作成することができる。
Builder#setSmallIcon()メソッド
Builder#setContentTitle()メソッド
Build#setContentText()メソッド
Build#setAutoCancel()メソッド
setAutoCancel(autoCancel: Boolean) //Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel.
setAutoCancel(true) を呼び出すと、ユーザーがタップした場合に自動的に通知が消去される。
Build#setContentIntent()メソッド
setContentIntent(intent: PendingIntent!)
//Supply a PendingIntent to send when the notification is clicked.
通知がクリックされたときにPendingIntentを供給する。
Builder#build()クラスメソッド
Combine all of the options that have been set and return a new Notification object. build()メソッドを実行すると、Notificationオブジェクトを返す。
PendingIntentの生成(必要であれば)
PendingIntent | Android デベロッパー | Android Developers PendingIntentがどのような働きをするのか分かっていない。ただし、pendingIntentを実装するためにintentを渡すことは分かっている。