Reputation: 21
In alarm Manager application. This is My Scheduler Class:
class AndroidAlarmScheduler(val context: Context) : AlarmScheduler {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
@SuppressLint("MissingPermission")
@RequiresApi(Build.VERSION_CODES.O)
override fun schedule(alarmData: AlarmData) {
val currentDate = LocalDateTime.now()
// Combine the current date with the provided time to create a LocalDateTime
val dateTimeToSchedule = LocalDateTime.of(currentDate.toLocalDate(), alarmData.time)
// Get the epoch milliseconds from LocalDateTime
val milliseconds = dateTimeToSchedule.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
val intent = Intent(context,AlarmCancelHandler::class.java)
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
milliseconds,
PendingIntent.getBroadcast(
context,
alarmData.id.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
Log.d("CHECKITOUT","ALARM SET")
}
override fun cancel(alarmData: AlarmData) {
alarmManager.cancel(
PendingIntent.getActivity(
context,
alarmData.id.toInt(),
Intent(context, AlarmCancelHandler::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
)
}
}
My Broadcast Receiver Code:
class AlarmCancelHandler : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("CHECKITOUT", "ON RECEIVE CANCEL")
val newIntent = Intent(context, AlarmReceiveActivity::class.java)
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
context?.startActivity(newIntent)
Log.e("CHECKITOUT", "Activity started successfully")
} catch (e: Exception) {
Log.e("CHECKITOUT", "Error starting activity: $e")
}
}
}
It works fine when app is in background - activity instantly comes to front on specified time, but when I remove the app from background Logcat shows OnReceive
and Activity Started but Activity is not launched
Upvotes: 1
Views: 173
Reputation: 1007584
You cannot launch activities from the background on modern versions of Android. Please display a Notification
instead.
Upvotes: 1