Android动态和静态BroadcastReceivers [英] Android dynamic and static BroadcastReceivers

查看:75
本文介绍了Android动态和静态BroadcastReceivers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在我的应用中插入一些提醒。他们每个人都有不同的时间。了解BroadcastReceiver的静态版本即使在应用未运行时也可以运行。仅当应用程序处于活动状态,在onPause上存储并在onResume上重新创建时才提供动态版本。
因为我要插入提醒,是否需要为每个提醒创建静态接收者?

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?

推荐答案

静态还是动态?提醒可能会设置更长的时间,之后才会被触发。因此,在您的情况下使用静态广播接收器会更安全。

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.

在清单文件中:

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

每个提醒的接收者是否独立?实际上,不是。您可以将所有提醒指向一个静态接收器,它将毫无问题地处理所有提醒。如果要区分需要执行不同操作的提醒类型,可以将一些stringExtra放入意图中,并将其提取到广播接收器的 if-else 语句中。这是一种方式。

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.

如果将来将提醒设置为较长的​​日期:您可能知道您正在使用alarmManager设置提醒。但是,如果重新启动系统,所有警报将被删除。因此,您可以考虑在提醒中添加某种形式的提示。您可以将有关提醒的信息存储在SharedPreferences / SQLite db或您喜欢的任何其他方法中,只要您可以轻松地从中读取和写入数据即可。然后,您需要在系统重启后重置警报。为此,您需要再添加一个 broadcastReceiver ,以监听系统重新启动操作是否完成并在收到该命令后运行。然后,您在此处重新创建警报,或运行单独的 intentService 将重新创建警报。

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.

在清单文件中:

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

这篇关于Android动态和静态BroadcastReceivers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆