In Android, the common way to communicate between components:
1, using the broadcast mechanism: Listen to the main page of specific broadcast events, business logic operations, other pages only need to send broadcasts according to demand
For example: In the common app structure, the left side is usually the menu bar, click the menu bar, the middle page changes. Send broadcast notification container change display fragment when clicking Menu
2, the use of interface mode: Activity to implement a specific interface, in the subclass or fragment to get the activity object, converted to a specific interface object, call the interface method
3, Event-driven mode: EventManager
Recently on the Internet to see eventbus this open source project, using subscribers and sender mode for information transfer is very suitable for project use, and the coupling can be reduced to very low!
This can be fully self-fulfilling according to business requirements, the main logic is: Register events, cancel monitoring, send events, it is important to note that event management using singleton mode is more appropriate, but need to pay attention to concurrency problems!
The code is as follows:
Import Java.util.arraylist;import java.util.hashmap;import Java.util.list;import Java.util.map;import Android.os.handler;import Android.os.looper;public class EventManager {public static class Message {public int-what; public Object obj; public static interface Oneventreceiver {public void onEvent (Message message); private static EventManager manager;private map<class, list<oneventreceiver>> Map = new Hashmap<class, List<oneventreceiver>> ();p rivate Handler Handler = new Handler (Looper.getmainlooper ());p ublic static EventManager Getdefault () {if (null = = Manager) {synchronized (Eventmanager.class) {if (null = = Manager) {manager = new Ev Entmanager ();}}} Return manager;} Private EventManager () {}public synchronized void Register (Class clazz, oneventreceiver receiver) {list< oneventreceiver> receivers = Map.get (clazz); if (null = = receivers) {receivers = new arraylist< Eventmanager.oneventreceiver> (); Map.put (Clazz, receivers);} Receivers.add (receiver);} Public synchronized void UnRegister (Class clazz) {map.remove (clazz);} Public synchronized void PostMessage (Class clazz, final message message) {list<oneventreceiver> receivers = Map.get (clazz); if (null! = receivers) {//Determines whether the main thread is Boolean isuithread = looper.getmainlooper () = = Looper.mylooper (); for (the final on Eventreceiver receiver:receivers) {if (!isuithread) {handler.post (new Runnable () {@Overridepublic void run () {receiver. OnEvent (message);}});} else {receiver.onevent (message);}}}}}More features need to be modified according to business needs, pay attention to concurrency Oh!!
Communication between Android components-event-driven