广播的使用

来源:互联网 发布:五线谱转吉他谱软件 编辑:程序博客网 时间:2024/06/05 13:34

先写一个类继承广播

import com.example.until.APPFinal;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AFReceiver extends BroadcastReceiver {
private BRInteraction brInteraction;


@Override
public void onReceive(Context context, Intent intent) {
// 这里接受广播 APPFinal.mAction是发送的广播标识
if (intent.getAction().equals(APPFinal.mAction)) {
int length = intent.getIntExtra("imagelength", 0);
brInteraction.AFMsgcallBack(length);
}
}


// 自定义接口实现对广告发送消息的处理
public interface BRInteraction {
public void AFMsgcallBack(int content);
}


public void setBRInteractionListener(BRInteraction brInteraction) {
this.brInteraction = brInteraction;
}
}

在需要接受广播的类里面注册广播

/**
* 注册广播的方法
*/
private void initBroadcastReciver() {

private IntentFilter intentFilter;
private AFReceiver mReceiver;
intentFilter = new IntentFilter();
intentFilter.addAction(APPFinal.mAction);
mReceiver = new AFReceiver();
// 注册此监听
mReceiver.setBRInteractionListener((BRInteraction) this);
registerReceiver(mReceiver, intentFilter);
}

在需要发送广播的地方

// 发送广播
Intent intent = new Intent(APPFinal.mAction);
intent.putExtra("imagelength", mImageModel.size());
sendBroadcast(intent);

0 0