ホーム
2022.3.8

kotlin 通知する

NotificationManagerを使ってチャンネルを登録します。(Android8.0以降必要)
NotificationManagerCompatを使ってシステムに通知を登録します。

MainActivity.kt

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.example.samplenotification.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

binding.btnTest.setOnClickListener {
val channelId = "com.example.sample_notification"
val channelName = "my channel"
val channelDescription = "This is a sample notification."

//Android 8.0 以上ではアプリの通知チャンネルを登録することが必要。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //---*0
val importance = NotificationManager.IMPORTANCE_DEFAULT //---*1
val channel = NotificationChannel(channelId, channelName, importance).apply {
description = channelDescription
}
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
}

//通知をシステムに登録しています。
val builder = NotificationCompat.Builder(this, channelId).apply {
setSmallIcon(R.drawable.ic_launcher_foreground) //---*2
setContentTitle("通知のタイトル")
setContentText("通知するメッセージ")
priority = NotificationCompat.PRIORITY_DEFAULT //---*3
}
val id = 0 //---*4
NotificationManagerCompat.from(this).notify(id, builder.build())
}
}
}

*1:VERSION_CODES.O ←これはゼロではなくオーです。

*2:表示の重要度を指定します。

IMPORTANCE_HIGH音が鳴り、ヘッドアップ通知として表示されます。
IMPORTANCE_DEFAULT 音が鳴り、通知アイコンが表示されます。
IMPORTANCE_LOW 音は鳴りません。通知アイコンは表示されます。
IMPORTANCE_MIN 音はなりません。通知アイコンは表示されません。
画面上部からスワイプすると存在します。

*3:表示の優先度を指定します。

PRIORITY_MAX音が鳴り、ヘッドアップ通知として表示されます。
PRIORITY_HIGH音が鳴り、ヘッドアップ通知として表示されます。
PRIORITY_DEFAULT音が鳴り、通知アイコンが表示されます。
PRIORITY_LOW音は鳴りません。通知アイコンは表示されます。
PRIORITY_MIN音はなりません。通知アイコンは表示されません。
画面上部からスワイプすると存在します。

*4:この値が同じ場合、すでに通知があると上書きされます。