class AlarmReceiver : BroadcastReceiver() {
companion object {
const val TAG = "AlarmReceiver"
const val NOTIFICATION_ID = 0
const val PRIMARY_CHANNEL_ID = "primary_notification_channel"
}
lateinit var notificationManager: NotificationManager
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "Received intent : $intent")
notificationManager = context.getSystemService(
Context.NOTIFICATION_SERVICE) as NotificationManager
createNotificationChannel()
deliverNotification(context)
}
private fun deliverNotification(context: Context) {
val contentIntent = Intent(context, MainActivity::class.java)
val contentPendingIntent = PendingIntent.getActivity(
context,
NOTIFICATION_ID,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val builder =
NotificationCompat.Builder(context, PRIMARY_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Alert")
.setContentText("This is repeating alarm")
.setContentIntent(contentPendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
notificationManager.notify(NOTIFICATION_ID, builder.build())
}
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
PRIMARY_CHANNEL_ID,
"Stand up notification",
NotificationManager.IMPORTANCE_HIGH
)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.description = "AlarmManager Tests"
notificationManager.createNotificationChannel(
notificationChannel)
}
}
}
class MainActivity : AppCompatActivity() {
private val TAG = MainActivity::class.java.simpleName
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val start = findViewById<Button>(R.id.start)
start.setOnClickListener {
Log.d(TAG, "start")
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlarmReceiver::class.java) // 1
val pendingIntent = PendingIntent.getBroadcast( // 2
this, AlarmReceiver.NOTIFICATION_ID, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
val repeatInterval: Long = AlarmManager.INTERVAL_FIFTEEN_MINUTES
val triggerTime = (SystemClock.elapsedRealtime() // 1
+ repeatInterval)
alarmManager.setInexactRepeating( // 2
AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerTime, repeatInterval,
pendingIntent)
Toast.makeText(this, "Toast", Toast.LENGTH_SHORT).show()
}
val end = findViewById<Button>(R.id.end)
end.setOnClickListener {
}
}
}
- 참조
https://codechacha.com/ko/android-alarmmanager/
https://developer.android.com/training/scheduling/alarms?hl=ko
'Android(Kotlin)' 카테고리의 다른 글
Simple ForegroundService (0) | 2022.10.15 |
---|---|
Android ROOM sqlcipher (0) | 2022.09.20 |
bottomNavigationView (0) | 2022.08.30 |
ViewModelFactory 오류 (0) | 2022.08.19 |
bumblebee 이상 firebase import (0) | 2022.08.12 |