はじめに
アプリ画面のボタンを押下すると通知が届く様にする
※コード以外省略
実装
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val channelId = "channel_id"
val channelName = "channel_name"
val channelDescription = "channel_description "
val notificationButton = findViewById<Button>(R.id.button)
///APIレベルに応じてチャネル作成
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = channelName
val descriptionText = channelDescription
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(channelId , name , importance).apply {
description = descriptionText
}
/// チャネル登録
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
/// 通知の中身
val builder = NotificationCompat.Builder(this , channelId)
.setSmallIcon(R.drawable.ic_launcher_background) /// アイコン
.setContentTitle("肉まん") /// タイトル
.setContentText("美味しい") /// コンテンツ
.setPriority(NotificationCompat.PRIORITY_DEFAULT) /// 通知の優先度
var notificationId = 0 /// notificationID
notificationButton.setOnClickListener {
/// ボタンを押して通知を表示
with(NotificationManagerCompat.from(this)) {
notify(notificationId , builder.build())
notificationId += 1
}
}
}
}
これだけ、、、
画像が通知の表示部分