Should BroadcastReceiver be declared inside activities?

别来无恙 提交于 2019-12-11 12:49:16

问题


I'm wondering what's the better cleaner design approach to handle BroadcastReceiver creation between those two:

  1. Declaring directly a BroadcastReceiver in an Activity/Fragment and overriding onReceived method there.

  2. Creating another custom receiver class in a package "receiver", that extends the BroadcastReceiver class and override onReceive. Then, you instantiate that custom receiver class in your Activity/Fragment.


回答1:


There are 2 types of Broadcast Receivers

1)Dynamic Broadcast Receiver that is registered inside activity

2)Static Broadcast Receiver that is registered or declared inside Manifest file with Receiver tag with specific action(when to fire the Receiver)

Uses:Eg say receive message

1) Dynamic Broadcast Receiver is used to receive the Broadcast intent mainly to refresh the message sent through send Broadcast method.

2)Static Broadcast Receiver is used to receive the message.Here the Registered Receiver with SMS receive action will receive the message and later it sent to activity

At last It depends on developer which one to use,when to use based on requirement




回答2:


There is no cleaner approach, it depends on how you Code.

Following the DRY principle, I only extend a BroadcastReceiver as soon as I notice I'll need them in different Activites.



来源:https://stackoverflow.com/questions/36521019/should-broadcastreceiver-be-declared-inside-activities

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