Android中EventBus详解

一、介绍

EventBus是一款针对Android优化的发布/订阅事件总线,他的主要功能的代替Intent,Handler,BroadCast在Service,Activity,Fragment中进行通信传递消息,他的优点是开销小,代码优雅简洁,易上手。

1、EventBus的开源库

源码:https://github.com/greenrobot/EventBus

2、基本使用方法

(1)自定义一个消息内容类

(2)在接收消息页面进行注册

(3)发送消息

(4)接收消息的页面实现(注意:实现方法有四个)

(5)在接收消息的页面解除注册

3、详解四个实现方法

(1)public void onEvent(MsgEvent1 msg)

如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在哪个线程中运行,发布事件和接收事件处于同一个线程。注意:使用此方法时,在onEvent方法中不能执行耗时的操作。

(2)public void onEventMainThread(MsgEvent1 msg)

如果使用onEventMainThread作为订阅函数,那么无论该事件是从哪个线程发布出来的,onEventMainThread都会在UI线程中执行。注意:1、Android只能在UI线程中更新UI;2、使用此方法时,在onEventMainThread方法中不能执行耗时的操作。

(3)public void onEventBackgroundThread(MsgEvent1 msg)

如果使用onEventBackgroundThread作为订阅函数,那么如果该事件是在UI线程中发布出来的,那么onEventBackgroundThread就会在子线程中执行;如果该事件是在子线程中发布出来的,那么onEventBackgroundThread直接在该子线程中执行。

(4)public void onEventAsync(MsgEvent1 msg)

如果使用onEventAsync作为订阅函数,那么无论该事件是哪个线程发布的,都会在创建一个新的子线程中执行。

二、实战

1、示例:

(1)、进入第一个面,模拟从服务器拿数据,拿到数据后更新UI;

(2)、第一个页面展示的多个人员信息,点击其中某一个进入到第二个页面,在第二个页面进行修改相关数据后,第一个页面的数据自动保存替换并更新UI;

Android中EventBus详解_第1张图片


2、搭建:

首页代码,实现了第一次进入延迟模拟获取网络数据,然后进行UI渲染

package com.tb.eventbusdemo.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.tb.eventbusdemo.R;
import com.tb.eventbusdemo.activity.module.User;

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

import java.util.ArrayList;


/**
 * Created by tangbin on 16/6/14.
 */
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
    private ListView lv_users;
    private UserAdapter userAdapter;
    private ProgressBar progressBar;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                ArrayList users = getUsers();
                EventBus.getDefault().post(users);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);

        lv_users = (ListView) findViewById(R.id.lv_users);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000); // 模拟延时
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mHandler.sendEmptyMessage(0);
            }
        }).start();
        lv_users.setOnItemClickListener(this);
    }


    @Subscribe
    public void onEventPostThread(ArrayList users) {
        userAdapter = new UserAdapter(this, users);
        lv_users.setAdapter(userAdapter);
        progressBar.setVisibility(View.GONE);
    }

    @Subscribe
    public void onEventPostThread(User u) {
        for (User s : userAdapter.getUsers()) {
            if (s.equals(u)) {
                int po = userAdapter.getUsers().indexOf(s);
                userAdapter.getUsers().set(po, u);
                break;
            }
        }
        userAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        Intent i = new Intent();
        i.setClass(this, UserInfoDetailActicity.class);
        i.putExtra("user", (User) userAdapter.getItem(position));
        startActivity(i);
    }

    private ArrayList getUsers() {
        ArrayList users = new ArrayList<>();
        User user = new User();
        user.setId("1");
        user.setName("张三");
        user.setAge("28岁");
        user.setSex("女");
        user.setBirthday("1990-1-2");
        users.add(user);

        User user1 = new User();
        user1.setId("2");
        user1.setName("李四");
        user1.setAge("23岁");
        user1.setBirthday("1930-2-3");
        user1.setSex("女");
        users.add(user1);

        User user2 = new User();
        user2.setId("3");
        user2.setName("王五");
        user2.setAge("24岁");
        user2.setSex("男");
        user2.setBirthday("3990-5-6");
        users.add(user2);

        User user3 = new User();
        user3.setId("4");
        user3.setName("赵六");
        user3.setAge("22岁");
        user3.setBirthday("1930-12-11");
        user3.setSex("女");
        users.add(user3);

        return users;
    }

}

详情页面,监听数据的修改并通知首页进行同步更新

package com.tb.eventbusdemo.activity;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import com.tb.eventbusdemo.R;
import com.tb.eventbusdemo.activity.module.User;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by tangbin on 16/6/14.
 */
public class UserInfoDetailActicity extends Activity {
    private EditText et_name;
    private EditText et_sex;
    private EditText et_birthday;
    private EditText et_age;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        et_name = (EditText) findViewById(R.id.et_name);
        et_sex = (EditText) findViewById(R.id.et_sex);
        et_birthday = (EditText) findViewById(R.id.et_birthday);
        et_age = (EditText) findViewById(R.id.et_age);
        user = (User) getIntent().getSerializableExtra("user");

        if (user != null) {
            et_age.setText(user.getAge());
            et_name.setText(user.getName());
            et_sex.setText(user.getSex());
            et_birthday.setText(user.getBirthday());
        }

        et_age.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                user.setAge(s.toString());
                EventBus.getDefault().post(user);
            }
        });

        et_sex.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                user.setSex(s.toString());
                EventBus.getDefault().post(user);
            }
        });

        et_birthday.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                user.setBirthday(s.toString());
                EventBus.getDefault().post(user);
            }
        });

        et_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                user.setName(s.toString());
                EventBus.getDefault().post(user);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}

源码地址:

http://download.csdn.net/detail/atangsir/9549801



       

你可能感兴趣的:(Android中EventBus详解)