0
0

More than 1 year has passed since last update.

android 通知 Kotlin

Posted at

はじめに

アプリ画面のボタンを押下すると通知が届く様にする
※コード以外省略

実装

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
            }
        }
    }
}

これだけ、、、
画像が通知の表示部分

スクリーンショット 2022-01-19 23.55.12.png

0
0
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
0
0