1

I'm stuck for days now trying to figure out what is wrong with my broadcast receiver and alarm manager , basically my broadcast receiver is not triggered when pushing a notification .

**This is my broadcast receiver class

class NotificationAlarmReceiver : BroadcastReceiver() {

   private lateinit var mAlarmManager  : AlarmManager
   private lateinit var mPowerManager: PowerManager
   override fun onReceive(context: Context?, intent: Intent?) {

       mAlarmManager = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
       Toast.makeText(context,"Broadcast Receiver is called",Toast.LENGTH_SHORT).show()
       
       val notificationPendingIntent = PendingIntent.getActivity(
           context, Constants.PENDINGINTENT_REQUEST_CODE,
           Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT
       )

      
       val intent = Intent(context, NotificationAlarmReceiver::class.java)
       intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
       val alarmPendingIntent = PendingIntent.getBroadcast(context, Constants.NOTIFICATION_ALARM_CODE, 
              intent, PendingIntent.FLAG_UPDATE_CURRENT)

                   when {
                       Build.VERSION.SDK_INT >= 23 -> {
                           mAlarmManager?.setAndAllowWhileIdle(
                               AlarmManager.ELAPSED_REALTIME_WAKEUP,
                               System.currentTimeMillis(),
                               alarmPendingIntent)
                       }
                       Build.VERSION.SDK_INT in 21..22 -> {
                           mAlarmManager.setExact(
                               AlarmManager.ELAPSED_REALTIME_WAKEUP,
                               System.currentTimeMillis(),
                               alarmPendingIntent
                           )

                       }
                   }

                 
                   NotificationCompat.Builder(context!!, Constants.NOTIFICATION_ID).apply {
                       setContentTitle("Notification Title")
                       setContentText("Notification Text")
                       setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
                       setContentIntent(notificationPendingIntent)
                       setDefaults(NotificationCompat.DEFAULT_SOUND)
                       setDefaults(NotificationCompat.DEFAULT_LIGHTS)
                       setChannelId(Constants.NOTIFICATION_ID)
                       priority = NotificationCompat.PRIORITY_HIGH
                       setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                       NotificationManagerCompat.from(context!!)
                           .notify(Constants.NOTIFICATION_REQUEST_CODE, build())
                   }
              } 

** Permission i have added in my manifest file

 <uses-permission android:name="android.permission.VIBRATE" />
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 <uses-permission android:name="android.permission.WAKE_LOCK" />

** Adding Receiver in my manifest file

```

<receiver android:name=".alarmManager.NotificationAlarmReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>

PS : I have to make a sample code to turn on / off airplane mode and registered the receiver dynamically
but with my code it is not triggered at all if anyone could guide me i d appreciate it , i ve been stuck for days 

Taki
  • 3,290
  • 1
  • 16
  • 41

1 Answers1

1

You can find fully working examples of working Alarm Manager here:

Alarm manager is not working with long term tasks

How to use Android AlarmManager in Fragment in Kotlin?

class InternetDaysLeftAlarm @Inject constructor(
    @ApplicationContext val context: Context
) {
    fun scheduleAlarm(triggerHour: Int = INTERNET_DAYS_LEFT_ALARM_DEFAULT_TRIGGER_HOUR) {
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, InternetDaysLeftReceiver::class.java)
        intent.action = INTENT_ACTION_INTERNET_DAYS_LEFT_ALARM
        val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0)

        // Calculating minutes until required trigger hour.
        // Converting minutes to millis for scheduling purposes.
        val msUntilTriggerHour: Long = TimeUnit.MINUTES.toMillis(minutesUntilOClock(triggerHour))

        // Calculating and adding jitter in order to ease load on server
        val jitter: Long = TimeUnit.MINUTES.toMillis(Random.nextInt(0, 420).toLong())

        val alarmTimeAtUTC: Long = System.currentTimeMillis() + msUntilTriggerHour + jitter

        // Enabling BootReceiver
        val bootReceiver = ComponentName(context, BootReceiver::class.java)
        context.packageManager.setComponentEnabledSetting(
            bootReceiver,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP
        )

        // Depending on the version of Android use different function for setting an Alarm.
        // setAlarmClock() => Android < Marshmallow
        // setExactAndAllowWhileIdle() => Android >= Marshmallow
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
            alarmManager.setAlarmClock(
                AlarmManager.AlarmClockInfo(alarmTimeAtUTC, pendingIntent),
                pendingIntent
            )
        } else {
            alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP,
                alarmTimeAtUTC,
                pendingIntent
            )
        }
    }
}
Vitaliy-T
  • 733
  • 6
  • 23
  • Thank you for your answer , what is the best place to put alarm manager code ? for now i'm putting it in my receiver class , should i switch it to main activiy ? – Taki Oct 27 '20 at 16:33
  • Well, the way I handled it is I just created a separate class `Alarms` and then had functions inside that would schedule an alarm that I need. I will edit my post with an example of how it looks. – Vitaliy-T Oct 27 '20 at 16:47
  • Thank you , i appreciate that – Taki Oct 27 '20 at 16:49
  • My issue is still not solved , i have created a seperate class called AlarmHelper where i set up the alarm manage and then i call it in my main activity , it still works only when i restart app – Taki Oct 28 '20 at 00:45
  • What do you mean "when I restart an app"? Let's say you have your alarm scheduled when the app is launched. It is scheduled to run 30 seconds after a launch on a foreground app. Is it triggered 30 seconds after a launch? – Vitaliy-T Oct 28 '20 at 08:40
  • Let's say time is 12:00 , i put a notification at 12:00 too , the notification should be triggered right away , in my case no , i need to restart app for it to be shown up , letalone that it dosnt work when i close app or reboot device – Taki Oct 28 '20 at 14:36
  • Alright, try the following then: Run the app and make Alarm manager schedule to run alarm 30 seconds after launch of the app and see if it works. – Vitaliy-T Oct 28 '20 at 14:40
  • in that case it works when i schedule for at 12:00 and when i open app when it is 12:00 it gets triggered , but in all other scenarios , it is not working and the reason why is because broadcast receiver is not being triggered at all – Taki Oct 28 '20 at 14:42
  • I have given you two links with 100% working implementations of Alarm Manager and Broadcast receiver that you can try to use. Are you using those? – Vitaliy-T Oct 28 '20 at 14:44
  • Yes i actually tried yours and i beleive your code works but the broadcast receiver is not the one triggered and i still don't understand why – Taki Oct 28 '20 at 14:45
  • I don't understand what you mean. If you schedule the alarm and it does work, then it means that the broadcast receiver was triggered – Vitaliy-T Oct 28 '20 at 14:46
  • Not really because it is only triggered if i put my code in the main activity which means that the notification code is only triggered in main activity but if i for example move the notification code to be executed in the broadcastt receiver , it dosnt trigger at all , not in any scenario , hope you got me – Taki Oct 28 '20 at 14:47
  • Do you trigger alarm manager code in your activity or broadcast receiver class ? – Taki Oct 28 '20 at 14:52
  • You already have explanation above: You schedule alarm in one class, then, in your broadcast receiver you execute the code that you need to execute when the alarm is triggered. You really have all the information that you need to figure this out – Vitaliy-T Oct 28 '20 at 14:54
  • This is my code in paste bin https://pastebin.pl/view/e587e86a ,as i mplemented the way you showed me but not working .. – Taki Oct 28 '20 at 15:14
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223770/discussion-between-taki-eddine-and-rj). – Taki Oct 28 '20 at 16:08