Android dynamic and static BroadcastReceivers

前端 未结 2 1344
余生分开走
余生分开走 2021-01-29 00:46

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. Dy

相关标签:
2条回答
  • 2021-01-29 01:11

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

    0 讨论(0)
  • 2021-01-29 01:23

    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>
    
    0 讨论(0)
提交回复
热议问题