接收
注册:分为两种,静态注册和动态注册
首先写一个类继承BroadCastReceiver
public class MyBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,intent.getStringExtra("name"),Toast.LENGTH_SHORT).show();
}
}
静态注册:
AndroidManifest.xm 的 <application>中
<receiver android:name=".ui.broadcastreceiver.MyBroadCastReceiver">
<intent-filter >
<action android:name="com.example.sample"/>
</intent-filter>
</receiver>
发现在android8.0当中静态广播接收不到,百度搜索一下有人说是8.0限制了静态注册
动态注册:
private MyBroadCastReceiver myBroadCastReceiver=new MyBroadCastReceiver();
@Override
protected void initView() {
IntentFilter intentFilter=new IntentFilter("com.example.sample");
registerReceiver(myBroadCastReceiver,intentFilter);
}
com.example.sample与发送广播时的字符串对应即可
发送
广播发送分为有序还是无序
无序广播,所有接收者都可以接收
Intent intent=new Intent();
intent.setAction("com.example.sample");
intent.putExtra("name","啦啦啦");
sendBroadcast(intent);
有序广播,按顺序接收
优先级1000到-1000
既然之前说到8.0不支持静态注册,那么我直接这样写
private MyBroadCastReceiver myBroadCastReceiver=new MyBroadCastReceiver();
private MyBroadCastReceiver1 myBroadCastReceiver1=new MyBroadCastReceiver1();
private MyBroadCastReceiver2 myBroadCastReceiver2=new MyBroadCastReceiver2();
@Override
protected void initView() {
IntentFilter intentFilter=new IntentFilter("com.example.sample");
intentFilter.setPriority(1000);
registerReceiver(myBroadCastReceiver,intentFilter);
IntentFilter intentFilter1=new IntentFilter("com.example.sample");
intentFilter.setPriority(0);
registerReceiver(myBroadCastReceiver1,intentFilter1);
IntentFilter intentFilter2=new IntentFilter("com.example.sample");
intentFilter.setPriority(-1000);
registerReceiver(myBroadCastReceiver2,intentFilter2);
}
@OnClick({R.id.no_order,R.id.order})
void sendBroad(View view){
switch (view.getId()){
case R.id.no_order:
break;
case R.id.order:
Intent intent=new Intent(); intent.setAction("com.example.sample");
sendOrderedBroadcast(intent,null,null,null,0,"啦啦啦",null);
break;
}
}
以下是三个接收数据类:
public class MyBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("data==",getResultData());
setResultData("修改数据");
}
}
public class MyBroadCastReceiver1 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("data1==",getResultData());
abortBroadcast();
}
}
public class MyBroadCastReceiver2 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("data2==",getResultData());
}
}
打印结果