「Android/kotlin/Notification」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==ローカル通知== 通知が来るようになる。通知バーを見にいくと、新規通知が、追加されてることを確認。 AndoridManifest.xml <pre>...」) |
(相違点なし)
|
2024年9月11日 (水) 16:51時点における版
ローカル通知
通知が来るようになる。通知バーを見にいくと、新規通知が、追加されてることを確認。
AndoridManifest.xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
kotlin
fun notification() {
val notificationId = 1
val channelId = "alarm_channel"
// Android 13 以上の場合、通知権限の確認が必要
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS
) != PackageManager.PERMISSION_GRANTED
) {
// 権限がなければリクエスト
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
1001 // リクエストコードは適当な値でOK
)
return // 権限が許可されるまで通知を表示しない
}
}
// 通知チャネルの設定(Android 8.0以上)
val notificationManager = NotificationManagerCompat.from(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelName = "Alarm Channel"
val channelDescription = "Channel for alarm notifications"
val importance = NotificationManager.IMPORTANCE_HIGH // 通知の重要度をHIGHに設定
val notificationChannel = NotificationChannel(channelId, channelName, importance).apply {
description = channelDescription
}
notificationManager.createNotificationChannel(notificationChannel)
}
// 通知の作成
val notification = NotificationCompat.Builder(this, channelId)
.setSmallIcon(android.R.drawable.ic_notification_overlay) // 通知アイコン
.setContentTitle("アラーム通知") // 通知タイトル
.setContentText("指定した時間が経過しました!") // 通知内容
.setPriority(NotificationCompat.PRIORITY_HIGH) // 優先度をHIGHに設定
.setDefaults(NotificationCompat.DEFAULT_ALL) // サウンド、振動などのデフォルト動作
.build()
// 通知を表示
notificationManager.notify(notificationId, notification)
}
