public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //动态注册广播接受者,优先级高于静态注册 IntentFilter intentFilter = new IntentFilter("BC_One"); BC2 bc2 = new BC2(); registerReceiver(bc2,intentFilter); } public void doClick(View v){ switch (v.getId()){ case R.id.button: //普通广播 Intent intent = new Intent(); intent.putExtra("msg","这是一条普通广播"); intent.setAction("BC_One"); sendBroadcast(intent); break; case R.id.button2: //有序广播 Intent intent2 = new Intent(); intent2.putExtra("msg","这是一条有序广播"); intent2.setAction("BC_Two"); sendOrderedBroadcast(intent2,null); break; case R.id.button3: //异步广播 可以先发送再注册 Intent intent3 = new Intent(); intent3.putExtra("msg","这是一条异步广播"); intent3.setAction("BC_Three"); sendStickyBroadcast(intent3); IntentFilter intentFilter = new IntentFilter("BC_Three"); BC3 bc = new BC3(); registerReceiver(bc,intentFilter); break; default: break; } }}//配置文件 /** priority -- 优先级 * 静态注册 *///普通广播接收public class BC1 extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String s = intent.getStringExtra("msg"); System.out.println("receive1收到的信息:"+s); }}public class BC2 extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String s = intent.getStringExtra("msg"); System.out.println("receive2收到的信息:"+s); }}//有序广播接收public class BC3 extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String s = intent.getStringExtra("msg"); System.out.println("receive3收到的信息:"+s); Bundle bundle = new Bundle(); bundle.putString("test","拦截广播添加数据"); setResultExtras(bundle); }}public class BC4 extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String s = intent.getStringExtra("msg"); System.out.println("receive4收到的信息:"+s); Bundle bundle = getResultExtras(true); String s2 = bundle.getString("test"); System.out.println("得到的处理结果是: "+s2); }}//异步广播接收public class BC5 extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { System.out.println("收到异地广播"); }}