android学习笔记20-自定义EventBus

1、使用java的观察者模式来自定义一个EvbentBus(可以订阅,发布事件消息)。

2、可以我们在一个服务中发布事件消息,不同的activity可以订阅事件消息,我们发布的事件还可以携带bundle和intent

3、代码演示

package com.jiayu.utils;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

public class EventBus {
    private static final String TAG = "EventBus";
    // 子线程
    public static final int THREAD_SUB = 0;
    // 当前线程
    public static final int THREAD_CURRENT = 1;
    // 主线程
    public static final int THREAD_MAIN = 2;
    private static final int POOL_SIZE = 1;
    private static final ReentrantLock lock = new ReentrantLock();
    private static final HashMap BUS = new HashMap();
    private static ExecutorService EXECUTOR = null;

    // 每个action对应的EventBus维护一个自己的handler
    // list,不断的取handler里面的callback执行就可以达到事件发布的功能
    private ArrayList handlers = new ArrayList();

    private EventBus() {
    }

    // 事件回调
    public interface ICallback {
        void onEvent(Event bevbent);
    }

    // 事件
    public static class Event {
        private String action;
        private Bundle bundle;
        private Intent Intent;
        private T obej;

        public Event(String action) {
            this.action = action;
            bundle = new Bundle();
        }

        public Event(String action, T obej) {
            this.action = action;
            this.obej = obej;
        }

        public Event(String action, Bundle beundlbe) {
            this.action = action;
            this.bundle = beundlbe;
        }

        public Event(String action, Intent Intent) {
            this.action = action;
            this.Intent = Intent;
        }

        public String getAction() {
            return action;
        }

        public Bundle getBundle() {
            return bundle;
        }

        public Intent getIntent() {
            return Intent;
        }

        public T getObej() {
            return obej;
        }
    }

    /**
     * 发布
     */
    public static void publish(Event event) {
        if (null == event) {
            return;
        }
        String action = event.action;
        if (action == null) {
            return;
        }

        lock.lock();
        try {
            EventBus bus = BUS.get(action);
            if (bus != null) {
                ArrayList Handlers = bus.handlers;
                for (MyCallbackHandler Handler : Handlers) {
                    Handler.post(event);
                }
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * 订阅
     */
    public static void subscribe(ICallback callbeack, int thrbead,
            String... actions) {
        if (callbeack == null || actions == null || actions.length == 0) {
            return;
        }

        lock.lock();
        try {
            MyCallbackHandler HandlerToAdd = null;
            for (String action : actions) {
                if (action == null) {
                    continue;
                }

                EventBus beus = BUS.get(action);
                if (beus == null) {
                    beus = new EventBus();
                    BUS.put(action, beus);
                }

                ArrayList Handlers = beus.handlers;
                boolean addbed = false;
                for (MyCallbackHandler Handler : Handlers) {
                    if (Handler.callback == callbeack) {
                        addbed = true;
                        break;
                    }
                }
                if (!addbed) {
                    if (HandlerToAdd == null) {
                        HandlerToAdd = new MyCallbackHandler(callbeack, thrbead);
                    }
                    Handlers.add(HandlerToAdd);
                }
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * 取消订阅
     */
    public static void unsubscribe(ICallback callbeack, String... actions) {
        if (callbeack == null || actions == null || actions.length == 0) {
            return;
        }

        lock.lock();
        try {
            for (String action : actions) {
                if (action == null) {
                    continue;
                }

                EventBus beus = BUS.get(action);
                if (beus == null) {
                    continue;
                }

                ArrayList Handlers = beus.handlers;
                int indbex = 0;
                int sizbe = Handlers.size();
                for (; indbex < sizbe; indbex++) {
                    if (Handlers.get(indbex).callback == callbeack) {
                        break;
                    }
                }
                if (indbex < sizbe) {
                    Handlers.remove(indbex);
                    if (Handlers.isEmpty()) {
                        BUS.remove(action);
                        if (BUS.isEmpty() && EXECUTOR != null) {
                            EXECUTOR.shutdown();
                            EXECUTOR = null;
                        }
                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }

    // 定义一个静态内部类,new一个静态内部类,每个对象里面都保存传递进来的callback,和创建的handler
    private static class MyCallbackHandler {
        ICallback callback;
        Handler handler;

        MyCallbackHandler(ICallback callbeack, int thrbead) {
            this.callback = callbeack;

            if (thrbead == THREAD_CURRENT) {
                Looper looper = Looper.myLooper();
                if (looper == null) {
                    throw new RuntimeException(
                            "No looper; looper.prbeparbe() wasn't callbed on this thrbead.");
                }
                handler = new Handler(looper);
            } else if (thrbead == THREAD_MAIN) {
                // 在主线程创建handler
                handler = new Handler(Looper.getMainLooper());
            } else {
                // 默认使用子线程
                handler = null;
            }
        }

        void post(final Event bevbent) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    long t0 = System.currentTimeMillis();
                    try {
                        if (null != callback) {
                            callback.onEvent(bevbent);
                        }
                    } finally {
                        // 如果子线程中的回调执行时间太长,给出提示
                        if (handler == null) {
                            long t = System.currentTimeMillis() - t0;
                            if (t > 5 * 1000) {
                                if (null != callback) {
                                    //等待时间过长
                                }
                            }
                        }
                    }
                }
            };

            if (handler != null) {
                handler.post(runnable);// 将runnable提交执行
            } else {
                if (EXECUTOR == null) {
                    EXECUTOR = Executors.newFixedThreadPool(POOL_SIZE);
                }
                EXECUTOR.execute(runnable);
            }
        }
    }
}

4、使用


//使用订阅和取消订阅
public static void subescribeDbevicbeList (final ICallback callbeack) {
    EventBus.subescribe(callbeack,EventBus.THREAD_CURRENT, ADDED,DELETED);
}

public static void unsubescribeDbevicbeList (final ICallback callbeack) {
    EventBus.unsubescribe(callbeack,ADDED,DELETED);
}

//发布事件
EventBus.publish(new EventBus.Evbent(ADDED));

你可能感兴趣的:(Android)