前言:个人编程习惯而言,喜欢把广播写成一个单例,便于开发维护,便于调用,便于管理。所以把曾经的一个广播助手类写在这里,当做范本,以后用到的话可以直接复制黏贴,稍作修改。广播其实无非就是3步:
1、注册registerReceiver;
2、发送sendBroadcast;
3、注销unregisterReceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import java.util.HashMap;
public class DemoBrcHelper {
public static final String ACTION = "Aciton";
/**
* 广播接收器
*/
private static HashMap<String, BroadcastReceiver> brHashMap;
/**
* 注册广播
*/
public static void register(Context ctx, String key, BroadcastReceiver br) {
if (null == brHashMap) {
brHashMap = new HashMap<>();
}
if (brHashMap.containsKey(key)) {
return;
}
brHashMap.put(key, br);
IntentFilter mfilter = new IntentFilter();
mfilter.addAction(ACTION);
ctx.registerReceiver(br, mfilter);
}
/**
* 注销广播
*/
public static void unregister(Context ctx, String key) {
if (null != brHashMap && brHashMap.containsKey(key)) {
ctx.unregisterReceiver(brHashMap.remove(key));
}
}
/**
* 发送广播
*/
public static void sendBroadcast(Context ctx) {
Intent it = new Intent(ACTION);
// it.putExtra("what", what);
ctx.sendBroadcast(it);
}
}