4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[kotlin] コピペでandroidに通知を出す

Posted at

#今回やること
ボタンを押したら通知を出せるようにする。
アクションボタンやその他オプションは今回は触れません。
こんなやつ ↓

#さっそくコピペ
activity_main.xmlにpushBtnのIDで適当にボタンを配置
そして以下をペースト

MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val CHANNEL_ID = "channel_id"
        val channel_name = "channel_name"
        val channel_description = "channel_description "

         ///APIレベルに応じてチャネルを作成
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = channel_name
            val descriptionText = channel_description
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                description = descriptionText
            }
            /// チャネルを登録
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }

        /// 通知の中身
        val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_launcher_background)    /// 表示されるアイコン
            .setContentTitle("ハローkotlin!!")                  /// 通知タイトル
            .setContentText("今日も1日がんばるぞい!")           /// 通知コンテンツ
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)   /// 通知の優先度

        
        var notificationId = 0   /// notificationID
        pushBtn.setOnClickListener {
            /// ボタンを押して通知を表示
            with(NotificationManagerCompat.from(this)) {
                notify(notificationId, builder.build())
                notificationId += 1
            }
        }

これで完了!! いやー思って以上に簡単でびっくり。

Android8.0(API26)から通知を出す際にチャネルの登録が必要になった。
notificationIDは適当に一意のものをつける。別に一意じゃなくても大丈夫だが、通知として表示される際IDが同じものは1個しか表示されないので注意。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?