What is the proper way to create and use a BroadcastReceiver for an alarm manager inside an Activity?
I did have a look at the following answers but it’s not clear to me whether I need to register the broadcast receiver and how to do so with the AlarmManager if it is. Also, it is not clear to me whether I should create the BroadcastReceiver inside the OnCreate() function or as class variable.
Kotlin AlarmManager and BroadcastReceiver not working
Background:
I am trying to make an app that:
-
Plays a song at a specific time
-
Updates the time when the song should next be played
I was able to get 1) to work by creating a separate file for the BroadcastReceiver file as is commonly done, but then I am unable to access the AlarmManager because it is only available in the AppCompatActivity class. I also tried to use an intent to move back to the main activity and set the new alarm there, but that also did work because BroadcastReceiver does not have a context.
I am now trying to have the BroadcastReceiver inside the MainActivity but it does not get triggered:
private lateinit var picker: MaterialTimePicker
private lateinit var alarmManager: AlarmManager
private lateinit var calendar: Calendar
val broadCastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
var mp = MediaPlayer.create(context, R.raw.song_title)
mp.setVolume(1.0f, 1.0f)
mp.start()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var calendar = Calendar.getInstance()
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
val newDate = Calendar.getInstance()
newDate.add(Calendar.MINUTE, 1)
calendar[java.util.Calendar.HOUR_OF_DAY] = newDate.get(Calendar.HOUR_OF_DAY)
calendar[java.util.Calendar.MINUTE] = newDate.get(Calendar.MINUTE)
calendar[java.util.Calendar.SECOND] = 0
calendar[java.util.Calendar.MILLISECOND] = 0
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
}
}
2
Answers
After tweaking this answer I got it to work:
I can confirm that registering the receiver is indeed required.
AlarmManager is not just only available in the AppCompatActivity class but from anywhere where you have access to Context as shown below: