先创建一个类继承广播,并且定义一个接口传递所需要的参数
public class ADReceiver extends BroadcastReceiver {
private BRInteraction brInteraction;
@Override
public void onReceive(Context context, Intent intent) {
// 广告发送消息后,这里接受广播(ADSendMsg为发送广播标识)
if (intent.getAction().equals("ADSendMsg")) {
String name = intent.getExtras().getString("name");
brInteraction.app2IsClosedcallBack(name);
}
}
// 自定义接口实现对广告发送消息的处理
public interface BRInteraction {
public void app2IsClosedcallBack(String content);
}
public void setBRInteractionListener(BRInteraction brInteraction) {
this.brInteraction = brInteraction;
}
}
在需要接受广播的类里面注册广播
Tip:这个方法的类里面需要继承广播的接口
private void initBroadcastReciver() {
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter .addAction("ADSendMsg");
myReceiver = new ADReceiver();
// 注册此监听
myReceiver.setBRInteractionListener(this);
registerReceiver(myReceiver, mIntentFilter);
}
在需要发送广播的地方
// 发送广播
private void sendBroadcastReciver() {
Intent intent = new Intent("ADSendMsg");
intent.putExtra("key", value);
sendBroadcast(intent);
}
网友评论