Android dynamic and static BroadcastReceivers

£可爱£侵袭症+ 提交于 2019-12-02 09:52:33

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>

While we define a dynamic broadcast receiver, the reminder will only trigger when the application is active to the user, if not the broadcast receiver won't get called and the user won't be able to get notified by the reminder. To do that the broadcast receiver must be declared static so that the reminder get triggered even if the application is closed. Just remember how the Alarm works :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!