问题
I'm wondering what's the better cleaner design approach to handle BroadcastReceiver creation between those two:
Declaring directly a BroadcastReceiver in an Activity/Fragment and overriding onReceived method there.
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