BroadcastrReceiver广播可以在不同的APP之间发广播,以便不同的app之间进行通信。两个app之间通过广播进行通信的时候,发送广播的一方不必去新建BroadcastrReceiver,只需要发送广播就行了。
发送端APP代码如下
Intent intent=new Intent();
//setAction就是指设置这条广播的描述信息,描述一下是做什么的,这个参数是自定义的
intent.setAction("com.aodlanucher.intent.startCall");
//setPackage就是指设置这条广播发给的指定app的包名,必须设置包名
intent.setPackage("com.example.myapplication");
//intent是可以携带一些信息的,key-value的形式,自己定义key值
String[] s=new String[2];
s[0]="2";
s[1]="13343289929";
intent.putExtra("boardInfo",s);
//activity下属的方法,发送广播
sendBroadcast(intent);
接收端APP首先需要写一个响应广播的广播类,这里必须重写onReceive方法,里面包含响应广播后需要执行的操作。
public class BoardCastReciever extends BroadcastReceiver {
@SuppressLint({"WrongConstant", "ShowToast"})
@Override
public void onReceive(Context context, Intent intent) {
String[] s=intent.getStringArrayExtra("boardInfo");
//取一下intent中所携带的参数
if(s!=null){
Toast.makeText(context, "收到上个的广播"+s[0]+s[1],1).show();
}
else {
Toast.makeText(context, "收到上个的广播",1).show();
}
//启动app的Activity
Intent intent1=new Intent(context,MainActivity.class);
context.startActivity(intent1);
}
}
如果想要广播生效,也就是能响应发来的信息
需要配置<AndroidMainifest文件>
<receiver
android:name=".BoardCastReciever"
>
<intent-filter>
//这里的action name 就是发送广播时自定义的字段,必须设置
<action android:name="com.aodlanucher.intent.startCall" />
</intent-filter>
</receiver>