【Android】封装BroadcastReceiver

代替eventBus等广播

这是Telegram的本地广播封装出来的,由兴趣的同学可以去github查看telegram的源代码

public class NotificationController {
    private static int totalEvents = 1;

    public static final int didReceiveSmsCode = totalEvents++;
    public static final int imOnline = totalEvents++;
    public static final int imOffline = totalEvents++;
    public static final int imNewMessage = totalEvents++;
    public static final int imRefreshList = totalEvents++;
    public static final int imGroupRemove = totalEvents++;
    public static final int imGroupDestroy = totalEvents++;
    public static final int emojiDidLoaded = totalEvents++;
    public static final int burnAfterRead = totalEvents++;
    public static final int groupChange = totalEvents++;
    public static final int sendMap = totalEvents++;
    public static final int changeGroupName = totalEvents++;
    public static final int closeActivity = totalEvents++;
    public static final int finishCurFragment = totalEvents++;
    public static final int UserRemoved = totalEvents++;
    public static final int loginAnotherDevice = totalEvents++;
    public static final int uploadPhoto = totalEvents++;
    public static final int blocklist = totalEvents++;
    public static final int cover = totalEvents++;
    public static final int syncedAccount = totalEvents++;
    public static final int avatarNeedChange = totalEvents++;
    public static final int getLocation = totalEvents++;
    public static final int groupInfoChange = totalEvents++;
    public static final int group = totalEvents++;
    public static final int messageChage = totalEvents++;
    public static final int groupUserChanger = totalEvents++;
    public static final int groupUserAdminChanger = totalEvents++;
    public static final int refreshExpressionFinish = totalEvents++;
    public static final int callMmessage = totalEvents++;
    public static final int profileUpdate = totalEvents++;
    public static final int refreshNoticeMsg = totalEvents++;
    public static final int momentOperation = totalEvents++;
    public static final int keyboardShow = totalEvents++;
    public static final int keyboardHide = totalEvents++;
    public static final int wantListRefresh = totalEvents++;
    public static final int topic = totalEvents++;
    public static final int syncGift = totalEvents++;
    public static final int gold = totalEvents++;//金币
    public static final int redPackets = totalEvents++;//红包
    public static final int burnTimer = totalEvents++;
    public static final int gift = totalEvents++;//礼物
    public static final int myProfit = totalEvents;//我的总收益

    private static final String BROADCAST_NOTIFICATION = "broadcast_notification";
    private static final String BROADCAST_NOTIFICATION_ID = "id";
    private static final String BROADCAST_NOTIFICATION_ARGS = "args";


    private final SparseArray<ArrayList<Object>> observers = new SparseArray<>();
    private final SparseArray<ArrayList<Object>> removeAfterBroadcast = new SparseArray<>();
    private final SparseArray<ArrayList<Object>> addAfterBroadcast = new SparseArray<>();
    private final ArrayList<DelayedPost> delayedPosts = new ArrayList<>(10);

    private int broadcasting = 0;
    private boolean animationInProgress;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;

    private int[] allowedNotifications;

    public interface NotificationControllerDelegate {
        void didReceivedNotification(int id, String... args);
    }

    private class DelayedPost {

        private DelayedPost(int id, String[] args) {
            this.id = id;
            this.args = args;
        }

        private final int id;
        private final String[] args;
    }

    private static volatile NotificationController Instance = null;


    public void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(ApplicationLoader.context);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BROADCAST_NOTIFICATION);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (action.equals(BROADCAST_NOTIFICATION)) {
                    int id = intent.getIntExtra(BROADCAST_NOTIFICATION_ID, 0);
                    if (id > 0) {
                        String[] args = intent.getStringArrayExtra(BROADCAST_NOTIFICATION_ARGS);
                        NotificationController.getInstance().postNotification(id, args);
                    }
                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    public void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }


    public static NotificationController getInstance() {
        NotificationController localInstance = Instance;
        if (localInstance == null) {
            synchronized (NotificationController.class) {
                localInstance = Instance;
                if (localInstance == null) {
                    Instance = localInstance = new NotificationController();
                }
            }
        }
        return localInstance;
    }

    private NotificationController() {
        broadcastManager = LocalBroadcastManager.getInstance(ApplicationLoader.context);
    }

    public void setAllowedNotificationsDutingAnimation(int notifications[]) {
        allowedNotifications = notifications;
    }

    public void setAnimationInProgress(boolean value) {
        animationInProgress = value;
        if (!animationInProgress && !delayedPosts.isEmpty()) {
            for (DelayedPost delayedPost : delayedPosts) {
                postNotificationInternal(delayedPost.id, true, delayedPost.args);
            }
            delayedPosts.clear();
        }
    }

    public boolean isAnimationInProgress() {
        return animationInProgress;
    }

    public void postNotification(int id, String... args) {
        if (Thread.currentThread() == ApplicationLoader.handler.getLooper().getThread()) {
            boolean allowDuringAnimation = false;
            if (allowedNotifications != null) {
                for (int allowedNotification : allowedNotifications) {
                    if (allowedNotification == id) {
                        allowDuringAnimation = true;
                        break;
                    }
                }
            }
            postNotificationInternal(id, allowDuringAnimation, args);
        } else {
            Intent intent = new Intent(BROADCAST_NOTIFICATION);
            intent.putExtra(BROADCAST_NOTIFICATION_ID, id);
            intent.putExtra(BROADCAST_NOTIFICATION_ARGS, args);
            broadcastManager.sendBroadcast(intent);
        }
    }

    private void postNotificationInternal(int id, boolean allowDuringAnimation, String... args) {
        if (Thread.currentThread() != ApplicationLoader.handler.getLooper().getThread()) {
            throw new RuntimeException("postNotification allowed only from MAIN thread");
        }

        if (!allowDuringAnimation && animationInProgress) {
            DelayedPost delayedPost = new DelayedPost(id, args);
            delayedPosts.add(delayedPost);
            if (Constants.DEBUG_VERSION) {
                Logger.e("Notification", "delay post notification " + id + " with args count = " + args.length);
            }
            return;
        }
        broadcasting++;
        ArrayList<Object> objects = observers.get(id);
        if (objects != null && !objects.isEmpty()) {
            for (int a = 0; a < objects.size(); a++) {
                Object obj = objects.get(a);
                ((NotificationControllerDelegate) obj).didReceivedNotification(id, args);
            }
        }
        broadcasting--;
        if (broadcasting == 0) {
            if (removeAfterBroadcast.size() != 0) {
                for (int a = 0; a < removeAfterBroadcast.size(); a++) {
                    int key = removeAfterBroadcast.keyAt(a);
                    ArrayList<Object> arrayList = removeAfterBroadcast.get(key);
                    for (int b = 0; b < arrayList.size(); b++) {
                        removeObserver(arrayList.get(b), key);
                    }
                }
                removeAfterBroadcast.clear();
            }
            if (addAfterBroadcast.size() != 0) {
                for (int a = 0; a < addAfterBroadcast.size(); a++) {
                    int key = addAfterBroadcast.keyAt(a);
                    ArrayList<Object> arrayList = addAfterBroadcast.get(key);
                    for (int b = 0; b < arrayList.size(); b++) {
                        addObserver(arrayList.get(b), key);
                    }
                }
                addAfterBroadcast.clear();
            }
        }
    }

    public void addObserver(Object observer, int id) {
        if (Thread.currentThread() != ApplicationLoader.handler.getLooper().getThread()) {
            throw new RuntimeException("addObserver allowed only from MAIN thread");
        }
        if (broadcasting != 0) {
            ArrayList<Object> arrayList = addAfterBroadcast.get(id);
            if (arrayList == null) {
                arrayList = new ArrayList<>();
                addAfterBroadcast.put(id, arrayList);
            }
            arrayList.add(observer);
            return;
        }
        ArrayList<Object> objects = observers.get(id);
        if (objects == null) {
            observers.put(id, (objects = new ArrayList<>()));
        }
        if (objects.contains(observer)) {
            return;
        }
        objects.add(observer);
    }

    public void removeObserver(Object observer, int id) {
        if (Thread.currentThread() != ApplicationLoader.handler.getLooper().getThread()) {
            throw new RuntimeException("removeObserver allowed only from MAIN thread");
        }
        if (broadcasting != 0) {
            ArrayList<Object> arrayList = removeAfterBroadcast.get(id);
            if (arrayList == null) {
                arrayList = new ArrayList<>();
                removeAfterBroadcast.put(id, arrayList);
            }
            arrayList.add(observer);
            return;
        }
        ArrayList<Object> objects = observers.get(id);
        if (objects != null) {
            objects.remove(observer);
        }
    }

    public void removeObserver(int id) {
        if (Thread.currentThread() != ApplicationLoader.handler.getLooper().getThread()) {
            throw new RuntimeException("removeObserver allowed only from MAIN thread");
        }
        if (broadcasting != 0) {
            ArrayList<Object> arrayList = removeAfterBroadcast.get(id);
            if (arrayList == null) {
                arrayList = new ArrayList<>();
                removeAfterBroadcast.put(id, arrayList);
            }
            arrayList.clear();
            return;
        }
        ArrayList<Object> objects = observers.get(id);
        if (objects != null) {
            objects.clear();
        }
    }

}

 

 

 

下面是用法

 

 

NotificationController.getInstance().postNotification(NotificationController.syncedAccount);

 

 

 

可以携带参数

 

 

NotificationController.getInstance().postNotification(NotificationController.closeActivity, PhotoSelectActivity.TAG, CameraActivity.TAG);

 

 

 

接收方

 

public class LaunchActivity extends FragmentActivity implements ActionBarLayout.ActionBarLayoutDelegate, NotificationController.NotificationControllerDelegate

 

 

 

只要实现了这个接口就可以

 

 

@Override
public void didReceivedNotification(int id, String... args) {
    if (id == NotificationController.closeActivity) {
        if (actionBarLayout == null) return;
        List<String> tags = new ArrayList<>();
        if (args != null && args.length > 0) {
            Collections.addAll(tags, args);

            for (int i = 0; i < actionBarLayout.fragmentsStack.size(); i++) {
                BaseActivity activity = actionBarLayout.fragmentsStack.get(i);
                if (tags.contains(activity.Tag())) {
                    activity.removeSelfFromStack();
                    i--;
                }
            }
        }
    }
}

 

 

 

 

如果哪里写的不好,或者有什么问题,我们可以随时交流 QQ179228838

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值