EventBus3.0使用详解

Posted datou_SleepyzzZ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EventBus3.0使用详解相关的知识,希望对你有一定的参考价值。

之前也提到过EventBus的使用方法

不过3.0之后EventBus使用方法有所改变,主要是处理订阅消息用了注解的方式。

还是先声明一下EventBus是发布/订阅事件总线。它可以让我们很轻松的实现在android各个组件之间传递消息,并且代码的可读性更好,耦合度更低。

比如:用来代替BroadReceiver、Handler更新UI、Fragment之间的数据传递等等...


如何使用EventBus3.0:

(1)首先自定义消息类,可以不继承人格其他类也不需要实现任何接口。如:

 

(2)在需要订阅事件的地方注册事件

(3)发送消息

(4)处理消息

在3.0之前,EventBus还没有使用注解方式。消息处理的方法也只能限定于onEvent、

onEventMainThread、onEventBackgroundThread和onEventAsync,分别代表四种线程模型。

而在3.0之后,消息处理的方法可以随便取名,但是需要添加一个注解@Subscribe,并且要指定线程模型(默认为PostThread)

事件处理函数的访问权限必须为public,否则会报异常

(5)取消消息订阅


至于消息处理的四种线程模型与之前版本同样,上篇文章有过介绍,就不再赘述。

前文链接http://blog.csdn.net/sleepyzzz1002/article/details/50908205


接下来通过一个小例子来体验下具体用法,例子来自http://blog.csdn.net/lmj623565791/article/details/47143563

将其中的BroadCast用EventBus3.0来代替,直接贴代码:

自定义消息类:

package com.sleepyzzz.itentservicedemo;

/**
 * User: datou_SleepyzzZ(SleepyzzZ19911002@126.com)
 * Date: 2016-05-22
 * Time: 20:55
 * FIXME
 */
public class MessageEvent 

    private String path;

    public MessageEvent(String path) 
        this.path = path;
    

    public String getPath() 
        return path;
    

    public void setPath(String path) 
        this.path = path;
    

ItentService类:

package com.sleepyzzz.itentservicedemo;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;

/**
 * User: datou_SleepyzzZ(SleepyzzZ19911002@126.com)
 * Date: 2016-05-22
 * Time: 20:07
 * FIXME
 */
public class UpLoadImgService extends IntentService

    private static final String ACTION_UPLOAD_IMG = "action.UPLOAD_IMG";

    public static final String EXTRA_IMG_PATH = "extra.IMG_PATH";

    public UpLoadImgService() 
        super("upload");
    

    //Create and Send a Work Request to an IntentService
    public static void startUpload(Context context, String path)
    
        Intent intent = new Intent(context, UpLoadImgService.class);
        intent.setAction(ACTION_UPLOAD_IMG);
        intent.putExtra(EXTRA_IMG_PATH, path);
        context.startService(intent);
    

    @Override
    protected void onHandleIntent(Intent intent) 
        if (intent != null)
        
            if (intent.getAction().equals(ACTION_UPLOAD_IMG))
            
                final String path = intent.getStringExtra(EXTRA_IMG_PATH);
                handleUploadImg(path);
            
        
    

    private void handleUploadImg(String path) 

        //广播
       /* try 
            Thread.sleep(3000);
            Intent localIntent = new Intent(MainActivity.UPLOAD_RESULT);
            localIntent.putExtra(EXTRA_IMG_PATH, path);
            LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
         catch (InterruptedException e) 
            e.printStackTrace();
        */

        try 
            Thread.sleep(3000);
            EventBus.getDefault().post(new MessageEvent(path));
         catch (InterruptedException e) 
            e.printStackTrace();
        

    

    @Override
    public void onCreate() 
        super.onCreate();
        Log.e("TAG", "onCreate");
    

    @Override
    public void onDestroy() 
        super.onDestroy();
        Log.e("TAG", "onDestroy");
    


主Activity

package com.sleepyzzz.itentservicedemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity 

    public static final String UPLOAD_RESULT = "result";
    @Bind(R.id.id_contanier)
    LinearLayout mIdContanier;

    @Bind(R.id.btn_add)
    Button mBtnAdd;

    /*private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver() 
        @Override
        public void onReceive(Context context, Intent intent) 
            if (intent.getAction().equals(UPLOAD_RESULT)) 
                String path = intent.getStringExtra(UpLoadImgService.EXTRA_IMG_PATH);
                TextView tv = (TextView) mIdContanier.findViewWithTag(path);
                tv.setText(path + " upload success ~~~ ");
            
        
    ;*/

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        /*IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPLOAD_RESULT);
        LocalBroadcastManager.getInstance(this).registerReceiver(uploadImgReceiver, intentFilter);*/

        //订阅事件
        EventBus.getDefault().register(this);
    

    //处理消息,用于更新UI
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showUploadResult(MessageEvent event)
    
        String path = event.getPath();
        TextView tv = (TextView) mIdContanier.findViewWithTag(path);
        tv.setText(path + " upload success ~~~ ");
    

    int i = 0;

    @OnClick(R.id.btn_add)
    public void onClick() 

        //模拟路径
        String path = "/sdcard/imgs/" + (++i) + ".png";
        UpLoadImgService.startUpload(this, path);

        TextView tv = new TextView(this);
        mIdContanier.addView(tv);
        tv.setText(path + " is uploading ...");
        tv.setTag(path);
    

    @Override
    protected void onDestroy() 
        super.onDestroy();
        //LocalBroadcastManager.getInstance(this).unregisterReceiver(uploadImgReceiver);

        //取消订阅
        EventBus.getDefault().unregister(this);
    



布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/id_contanier"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="AddTask"/>

</LinearLayout>





以上是关于EventBus3.0使用详解的主要内容,如果未能解决你的问题,请参考以下文章

EventBus3.0源码解读

Android编程入门--开源框架EventBus

EventBus3.0源码解析

EventBus3.0源码分析

EventBus3.0源码分析

EventBus3.0源码分析