Search code examples
androidbroadcastreceiver

Android dynamic and static BroadcastReceivers


I'm about to insert some reminders on my app. Each of them will have different time. Reading about BroadcastReceiver the static version runs even when an app isn't running. Dynamic version only when app is alive, being destoyed on onPause and recreated on onResume. Because I'm inserting reminders, do I need to create static receivers for each of my reminders or not? Is the right way to handle reminders with different times?


Solution

  • Static or Dynamic? We may assume that reminders may be set for some longer periods of time after which it will be triggered. Therefore, it is safer to use static broadcast receiver in your case.

    In your Manifest file:

    <receiver android:name=".YourBroadcastReceiver"/>
    

    Separate receiver for each reminder? Actually, no. You can point all of the reminders to one static receiver and it will handle all of them with no problems. If you want to separate between types of reminders that will need to do different actions, you may put some stringExtra to your intent and extract that in if-else statement in your broadcast receiver. That's one way.

    If reminders were set to significantly long date in future: You might know that you are setting reminders using alarmManager. However, all of the alarms are deleted if system is rebooted. Therefore, you may consider adding some sort of back to your reminders. You can store information about the reminders in SharedPreferences/SQLite db or any other method you prefer as long as you can easily read and write data from it. Then you need to reset alarms after system reboot. For this purposes you need to add one more broadcastReceiver that will listen for system reboot action being completed and run when it receives it. Then you recreate your alarms there or run separate intentService that will recreate alarms.

    In your Manifest file:

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
    <receiver android:name=".BootCompletedReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>