EventBus使用与分析

写在前面

EventBus是一款针对Android优化的发布(publish)/订阅(subscribe)事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。如有不当还请原谅指出。

    哪里可以获得

      1.开源库传送门: https://github.com/greenrobot/EventBus
      2.jar包下载: http://download.csdn.net/detail/luzhenyuxfcy/9461662

     怎么使用

      1.官方介绍: http://greenrobot.org/eventbus/
      2.鸿翔大神博客: http://blog.csdn.net/lmj623565791/article/details/40920453
      3.本博客: http://blog.csdn.net/luzhenyuxfcy/article/details/50893700

使用方式

快速上手

注册方法:

EventBus.getDefault().register(Object subscriber);

反注册方法:

EventBus.getDefault().unregister(Object subscriber); 这个要在销毁的时候调用

接收回调:

1、onEvent  
如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
2、onEventMainThread
如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
3、onEventBackground
如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
4、onEventAsync
使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.

发送事件:

EventBus.getDefault().post(Object);

使用过程

我将我的使用过程记录如下,走了不少弯路,简记之:( 我使用的版本是version = 3.0),因为我遇到如果不写“@Subscribe”注解,会报错的问题。错误如下:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lzy.evbusdemo/com.lzy.evbusdemo.OtherActivity}: org.greenrobot.eventbus.EventBusException: Subscriber class com.lzy.evbusdemo.OtherActivity and its super classes have no public methods with the @Subscribe annotation
我记得以前看前辈的代码并没有这个,应该是EventBus规范标准了吧,不然不知道怎么去写这几个方法回调。
创建项目EventBusDemo,主要是点击跳转后在第二个Activity(发送者)中发送事件,凡是注册EventBus的Activity(订阅者)均会回调数据
EventBus使用与分析_第1张图片
EventBus使用与分析_第2张图片 EventBus使用与分析_第3张图片
布局不再赘述,EventBus是事件总线,它是通过发送消息事件Event,然后订阅者会接到这个Event,那么我们先定义一个Event,也就是我们要发送的事件对象MyEvent
package com.lzy.evbusdemo;

public class MyEvent {
	
	private String msg;
	public MyEvent(String msg) {
		this.msg = msg;
	}

	public String getMsg() {
		return msg;
	}
}
其他两个主文件
package com.lzy.evbusdemo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {
	
	private TextView tvShowTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvShowTextView = (TextView) findViewById(R.id.tvShow);
        EventBus.getDefault().register(this);// 订阅
    }
    
    public void jumpTo(View view) {
		startActivity(new Intent(this, OtherActivity.class));
	}
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	EventBus.getDefault().unregister(this);
    }
   
    /**
     * 接收
     * */
    
    @Subscribe
    public void onEvent(MyEvent event) {
    	Log.i("Main", "Main - onEvent: " + event.getMsg());
	}

    @Subscribe
    public void onEventAsync(MyEvent event) {
    	Log.i("Main", "Main - onEventAsync: " + event.getMsg());
    }

    @Subscribe
    public void onEventBackgroundThread(MyEvent event) {
    	Log.i("Main", "Main - onEventBackgroundThread: " + event.getMsg());
    }
    
    @Subscribe
    public void onEventMainThread(MyEvent event) {
		Log.i("Main", "Main - onEventMainThread: " + event.getMsg());
		tvShowTextView.setText(event.getMsg());
	}
}
package com.lzy.evbusdemo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

public class OtherActivity extends Activity {
	
	private TextView textView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_other);
		EventBus.getDefault().register(this);
		textView = new TextView(this);
		textView.setText(getResources().getString(R.string.Text_Other_Activity));
		addContentView(textView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		textView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				EventBus.getDefault().post(new MyEvent("LD"));// 发布
			}
		});
	}

	@Override
    protected void onDestroy() {
    	super.onDestroy();
    	EventBus.getDefault().unregister(this);
    }
	
	/**
     * 接收
     * */
	
	@Subscribe
	public void onEvent(MyEvent event) {
		Log.i("Other", "Other - onEvent: " + event.getMsg());
	}

	@Subscribe
	public void onEventAsync(MyEvent event) {
		Log.i("Other", "Other - onEventAsync: " + event.getMsg());
	}
	
	@Subscribe
    public void onEventBackgroundThread(MyEvent event) {
    	Log.i("Other", "Other - onEventBackgroundThread: " + event.getMsg());
    }
    
	@Subscribe
	public void onEventMainThread(MyEvent event) {
		Log.i("Other", "Other - onEventMainThread: " + event.getMsg());
		textView.setText(event.getMsg());
	}
}
通过以上我们就实现了订阅与分发,只要是订阅者,在发送的时候就都能收到了。不过这几个方法我们应该使用哪个呢,还有他们是怎么调用的呢?上述代码调试信息如下
04-08 06:18:47.657: I/Main(1570): Main - onEvent
04-08 06:18:47.657: I/Main(1570): Main - onEventAsync
04-08 06:18:47.661: I/Main(1570): Main - onEventBackgroundThread
04-08 06:18:47.661: I/Main(1570): Main - onEventMainThread
04-08 06:18:47.661: I/Other(1570): Other - onEvent
04-08 06:18:47.661: I/Other(1570): Other - onEventAsync
04-08 06:18:47.661: I/Other(1570): Other - onEventBackgroundThread
04-08 06:18:47.661: I/Other(1570): Other - onEventMainThread
怎么都执行了呢?????我们注意到注解中有“@Subscribe”,我们了解过注解( http://blog.csdn.net/zhangweiwtmdbf/article/details/30246149)这是在回调中去找EvetBus的接收者,这应该不是,那只有里面的参数了,对试试~  我尝试创建了另外三个事件MyEvent1 ,MyEvent2 ,MyEvent3,代码和MyEvent处理一样。然后分发不同的消息,这四个回调分别去接收不同的消息,最终代码变成如此:
package com.lzy.evbusdemo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {
	
	private TextView tvShowTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvShowTextView = (TextView) findViewById(R.id.tvShow);
        EventBus.getDefault().register(this);// 订阅
    }
    
    public void jumpTo(View view) {
		startActivity(new Intent(this, OtherActivity.class));
	}
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	EventBus.getDefault().unregister(this);
    }
   
    /**
     * 接收
     * */
    
    @Subscribe
    public void onEvent(MyEvent event) {
    	Log.i("Main", "Main - onEvent: " + event.getMsg());
	}

    @Subscribe
    public void onEventAsync(MyEvent1 event) {
    	Log.i("Main", "Main - onEventAsync: " + event.getMsg());
    }

    @Subscribe
    public void onEventBackgroundThread(MyEvent2 event) {
    	Log.i("Main", "Main - onEventBackgroundThread: " + event.getMsg());
    }
    
    @Subscribe
    public void onEventMainThread(MyEvent3 event) {
		Log.i("Main", "Main - onEventMainThread: " + event.getMsg());
		tvShowTextView.setText(event.getMsg());
	}
}
package com.lzy.evbusdemo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

public class OtherActivity extends Activity {
	
	private TextView textView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_other);
		EventBus.getDefault().register(this);
		textView = new TextView(this);
		textView.setText(getResources().getString(R.string.Text_Other_Activity));
		addContentView(textView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		textView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				EventBus.getDefault().post(new MyEvent("LD"));// 发布
				EventBus.getDefault().post(new MyEvent1("DCM"));
				EventBus.getDefault().post(new MyEvent2("HY"));
				EventBus.getDefault().post(new MyEvent3("JSM"));
			}
		});
	}

	@Override
    protected void onDestroy() {
    	super.onDestroy();
    	EventBus.getDefault().unregister(this);
    }
	
	/**
     * 接收
     * */
	
	@Subscribe
	public void onEvent(MyEvent event) {
		Log.i("Other", "Other - onEvent: " + event.getMsg());
	}

	@Subscribe
	public void onEventAsync(MyEvent3 event) {
		Log.i("Other", "Other - onEventAsync: " + event.getMsg());
	}
	
	@Subscribe
    public void onEventBackgroundThread(MyEvent1 event) {
    	Log.i("Other", "Other - onEventBackgroundThread: " + event.getMsg());
    }
    
	@Subscribe
	public void onEventMainThread(MyEvent2 event) {
		Log.i("Other", "Other - onEventMainThread: " + event.getMsg());
		textView.setText(event.getMsg());
	}
}
运行一下:
04-08 07:18:58.717: I/Main(2008): Main - onEvent: LD ----------------------------------------- MyEvent
04-08 07:18:58.717: I/Other(2008): Other - onEvent: LD ----------------------------------------- MyEvent
04-08 07:18:58.717: I/Main(2008): Main - onEventAsync: DCM ----------------------------------------- MyEvent1
04-08 07:18:58.717: I/Other(2008): Other - onEventBackgroundThread: DCM ----------------------------------------- MyEvent1
04-08 07:18:58.717: I/Main(2008): Main - onEventBackgroundThread: HY ----------------------------------------- MyEvent2
04-08 07:18:58.717: I/Other(2008): Other - onEventMainThread: HY ----------------------------------------- MyEvent2
04-08 07:18:58.717: I/Main(2008): Main - onEventMainThread: JSM ----------------------------------------- MyEvent3
04-08 07:18:58.717: I/Other(2008): Other - onEventAsync: JSM ----------------------------------------- MyEvent3
发现果真如此。
至此,基本使用就是这些,我们继续往下看原理:

源码分析

上面已经说了回调是通过注解的方式来找到回调的,那肯定要先告诉EventBus谁是接收者吧,也就是注册register方法。
EventBus使用与分析_第4张图片
注册即往List subscriberMethods中添加方法对象,核心在findSubscriberMethods方法,我们先不看他怎么找的,因为在回调的时候也会通过这个来找,我们先看怎么加入的(到注册表中):subscribe(subscriber, subscriberMethod);
int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

        List> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // Existing sticky events of all subclasses of eventType have to be considered.
                // Note: Iterating over all events may be inefficient with lots of sticky events,
                // thus data structure should be changed to allow a more efficient lookup
                // (e.g. an additional map storing sub classes of super classes: Class -> List).
                Set, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry, Object> entry : entries) {
                    Class candidateEventType = entry.getKey();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }

订阅者方法实体是SubscriberMethod,定义了一系列属性


看到了一个subscribedEvents.add(eventType);注册事件类型它是 Class
所以也就验证了那四个回调是通过什么区分的这一论证;
EventBus使用与分析_第5张图片
根据循环找出不同类型的事件分开保存。执行肯定是通过Method的invoke方法:
EventBus使用与分析_第6张图片

反注册就很简单了,从Map中根据键remove掉
EventBus使用与分析_第7张图片
我们回过头看findSubscriberMethods方法
先从方法池中获取方法:List subscriberMethods = METHOD_CACHE.get(subscriberClass);然后分两种情况

第一种核心:
private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        for (Method method : methods) {
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 1) {
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        Class eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
                } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                    String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                    throw new EventBusException("@Subscribe method " + methodName +
                            "must have exactly 1 parameter but has " + parameterTypes.length);
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException(methodName +
                        " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
            }
        }
    }
筛选:
EventBus使用与分析_第8张图片
第二种核心
private SubscriberInfo getSubscriberInfo(FindState findState) {
        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }
        }
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }


返回符合的:
EventBus使用与分析_第9张图片
看一下post方法:
初始化队列并添加事件到队列:
PostingThreadState postingState = currentPostingThreadState.get();
List eventQueue = postingState.eventQueue;
eventQueue.add(event);然后就一直在寻找可以接收的接受者: 
    
   
EventBus使用与分析_第10张图片
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
        CopyOnWriteArrayList subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    postToSubscription(subscription, event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }
将对应事件所有的找到后

根据类型去执行方法,也就是发送给所有符合定义的事件的那四个方法类型:
EventBus使用与分析_第11张图片

栗子下载

下载

【欢迎上码】

【微信公众号搜索 h2o2s2】


你可能感兴趣的:(初探框架,Android进阶,通用工具)