I have a problem, I'm trying to trigger a notification with alarm manager. But as soon as the device enters idle mode, The notification does not pop up for me, it only appears after entering the application
this is my code in activity:
val intent = Intent(applicationContext, AlarmReceiver::class.java)
intent.putExtra(TITLE_EXTRA, "title")
intent.putExtra(MESSAGE_EXTRA, "adb shell dumpsys deviceidle step\n")
val pendingIntent = PendingIntent.getBroadcast(
applicationContext,
NOTIFICATION_ID,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 2 * 60000,
pendingIntent
)
this is my code alarmReciver:
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(intent.getStringExtra(TITLE_EXTRA))
.setContentText(intent.getStringExtra(MESSAGE_EXTRA))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.build()
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(NOTIFICATION_ID, builder)
}
}
and i use
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
in menifest.
What can I do so that the notification pops up for me even in idle/doze mode?
Since Android 12, you need to request runtime permission for SCHEDULE_EXACT_ALARM, and even then you are not guaranteed to receive it in time (but very very likely)
There are also two limitations that I came across that you need to communicate somehow to the user:
I have the same usecase in my app (show notification at exact time) and it works in most cases, but it still can happen that it fires up to 2h later when system is in doze mode or device have low battery optimizations running