【Android】封装BroadcastReceiver

来源:互联网 发布:网络教育2.5年毕业 编辑:程序博客网 时间:2024/06/05 17:50

今天发了好几篇文章了, 就不说明,反正对于伸手党来说只需要代码就够用,直接上代码


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

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


@Overridepublic 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

原创粉丝点击