Communication Mode between Android Application modules, android Module
Android Application Development usually requires multiple modules for Communication (mutual calls). If you do not pay attention to coupling, future function expansion and adjustment will make the code very messy and prone to errors, and difficult to maintain. For example, Fragment uses its public member method directly by getActivity (). Fragment and MainActivity are tightly coupled.
1 public class FragmentPage{2 ...3 public void onClick(View v){4 ...5 (MainActivity) getActivity().switchTab(MainActivity.RECOMMEND_TAB);6 ...7 }8 }9
First, let's look at several common coupling types: 1. Simple data parameter coupling. The two modules only use the basic data type to transmit information, which is generally acceptable. 2. Simple Object coupling. An object creates another object. In general, this is fine, but in some cases, for unit testing, network objects need to be configured, which requires dependency injection to solve the problem. 3. semantic Coupling. A module does not directly operate on another module in the form of an interface. For example, in the example above, Fragment converts an Activity reference to its subclass for use. We should avoid semantic coupling whenever possible. So how can we avoid tight coupling? First, you can use the first interface to allow other classes to communicate with them through interfaces.
public class FragmentPage{ private TabSwitcher mTabSwitcher; ... public FragmentPage(TabSwitcher switcher){ mTabSwitcher = switcher; } public void onClick(View v){ ... mTabSwitcher (TabSwitcher.RECOMMEND_TAB); ... }}
In large-scale Android Application Development, we may need to notify multiple classes of an event. If it is implemented simply through an interface, a large number of interfaces will be generated, in addition, the Message Receiver queue needs to be maintained to increase program complexity. Therefore, we need a solution that can manage the subscription-publish relationship: MessageBus. This communication mode is based on the subscription-publish design mode. The publisher can publish a message. The class or module that subscribes to the message is notified, so that the two are completely separated. Android provides a broadcast method that allows Intent to be transmitted between different applications. However, when passing complex data objects, you must implement the Serializable or Parcelable interface. Currently, event-based MessageBus are more popular and support custom events. Related EventBus include greenrobot EventBus and square otto. References: http://vinsol.com/blog/2014/11/04/communication-patterns-for-application-components/