The Alarm Manager allows scheduling the alarms based on time. An alarm can be one-time or repeated. By using the alarms, we can perform tasks at certain point of time.
We need to create a broadcast receiver which will be executed when the alarm was triggered.
package com.example.app
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
class AlarmReceiver : BroadcastReceiver()
{
override fun onReceive(context: Context, intent: Intent)
{
Log.d("MY_APP", "Alarm triggered")
}
}
A newly created broadcast receiver should be registered in the manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<application>
<!-- ... -->
<activity android:name=".MainActivity">
<!-- ... -->
</activity>
<receiver android:name=".AlarmReceiver" />
</application>
</manifest>
In order to schedule an alarm, we need to create a PendingIntent
. This intent can point to BroadcastReceiver
. It receives a broadcast from the system alarm service when the alarm was triggered.
The AlarmManager
object contains some methods which are used to schedule alarms. The setInexactRepeating()
method can be used to schedule the alarm which will be repeated based on specified interval.
Starting from Android 4.4 (API level 19), all the alarms are inexact. It was done to minimize device wake-ups and save battery life.
Starting from Android 5.1 (API level 22), there is a minimum interval of 1 minute for repeating alarms.
Starting from Android 6.0 (API level 23), alarms do not triggered when the device is idle in doze mode. In this case, we can use the setAndAllowWhileIdle()
or setExactAndAllowWhileIdle()
method to allow the execution of alarms when the device is in doze mode. To prevent alarms to fire off too frequently, the system triggers an alarm not more than once per 15 minutes. There is no method to wake up the device while in doze mode for a repeating alarm.
package com.example.app
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val requestCode = 1
val intent = Intent(this, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
this,
requestCode,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val triggerTime = System.currentTimeMillis()
val repeatInterval = 60000L // 1 minute
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
triggerTime,
repeatInterval,
pendingIntent
)
}
}
Leave a Comment
Cancel reply