Android dynamic and static BroadcastReceivers

99封情书 提交于 2019-12-09 03:48:53

问题


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?


回答1:


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>



回答2:


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 :)



来源:https://stackoverflow.com/questions/40354018/android-dynamic-and-static-broadcastreceivers

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