package com.example.myapplication.utils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.text.TextUtils; import androidx.localbroadcastmanager.content.LocalBroadcastManager; /** * 广播管理类 */ public class ReceiverManager { //退出登录 public static final String ACTION_LOGIN_OUT = "com.cunduoduo.action.loginout"; //刷新token public static final String ACTION_TOKEN_UPDATE = "com.cunduoduo.action.token.update"; //头像更改 public static final String ACTION_USER_PHOTO_UPDATE = "com.cunduoduo.user.photo"; public static final String THREAD_TAG = "threadTag"; private LocalBroadcastManager manager; private static ReceiverManager receiverManager; /** * 实例化 */ public synchronized static ReceiverManager getIntance() { if (receiverManager == null) { receiverManager = new ReceiverManager(); } return receiverManager; } /** * 注册广播 */ public void registerReceiver(Context context, BroadcastReceiver receiver, String... filters) { if (filters == null || filters.length == 0) { return; } manager = LocalBroadcastManager.getInstance(context); IntentFilter filter = new IntentFilter(); for (String s : filters) { filter.addAction(s); } manager.registerReceiver(receiver, filter); } /** * 取消注册 */ public void unRegisterReceiver(BroadcastReceiver receiver) { manager.unregisterReceiver(receiver); } /** * 发送广播 */ public void sendBroadCastReceiver(Context context, String... filter) { sendBroadCastReceiver(null, context, filter); } public void sendBroadCastReceiver(String params, Context context, String... filter) { if (filter == null || filter.length == 0) { return; } manager = LocalBroadcastManager.getInstance(context); Intent intent = new Intent(); if (!TextUtils.isEmpty(params)) { intent.putExtra(THREAD_TAG, params); } for (String s : filter) { manager.sendBroadcast(intent.setAction(s)); } } }