這篇博文介紹有序廣播的使用ide
和普通廣播徹底相同,只須要更換髮送的方式便可spa
ordered.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(); intent.putExtra("test","有序廣播"); intent.setAction("NORMAL"); //設定廣播的Action,用於過濾 sendOrderedBroadcast(intent,null); } });
在有序廣播的傳播過程當中,優先級高的Receiver能夠傳遞消息給低優先級的Receiver,甚至截斷廣播,具體操做以下:code
傳遞消息:blog
public class BC1 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String text=intent.getStringExtra("test"); Toast.makeText(context,"BC1"+text,Toast.LENGTH_SHORT).show(); Bundle bundle =new Bundle(); bundle.putString("test","修改"); setResultExtras(bundle); } }
public class BC2 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String text=intent.getStringExtra("test"); Bundle bundle=getResultExtras(true); String s=bundle.getString("test"); Toast.makeText(context,"BC2"+text+s,Toast.LENGTH_SHORT).show(); } }
在高優先級的Receiver中,經過Bundle數據包傳輸數據,並經過setResultExtras方法來發送數據。在低優先級的接受者中,則經過getResultExtras來獲取Bundle數據包,進而獲取數據。get
截斷消息:io
public class BC1 extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String text=intent.getStringExtra("test"); Toast.makeText(context,"BC1"+text,Toast.LENGTH_SHORT).show(); abortBroadcast(); } }
只須要在高優先級的接收者中調用abortBroadcast方法便可。ast