廣播 :在Android中,Broadcast是一種普遍運用的在應用程序之間傳輸信息的機制。咱們拿廣播電臺來作個比方。咱們日常使用收音機收音是這樣的:許許多多不一樣的廣播電臺經過特定的頻率來發送他們的內容,而咱們用戶只須要將頻率調成和廣播電臺的同樣就能夠收聽他們的內容了。Android中的廣播機制就和這個差很少的道理,Android廣播分爲兩個方面:廣播發送者和廣播接收者,一般狀況下,BroadcastReceiver指的就是廣播接收者(廣播接收器)。html
從實現原理看上,Android中的廣播使用了觀察者模式,基於消息的發佈/訂閱事件模型。所以,從實現的角度來看,Android中的廣播將廣播的發送者和接受者極大程度上解耦,使得系統可以方便集成,更易擴展。具體實現流程要點粗略歸納以下:java
1.廣播接收者BroadcastReceiver經過Binder機制向AMS(Activity Manager Service)進行註冊;android
2.廣播發送者經過binder機制向AMS發送廣播;git
3.AMS查找符合相應條件(IntentFilter/Permission等)的BroadcastReceiver,將廣播發送到BroadcastReceiver(通常狀況下是Activity)相應的消息循環隊列中;github
4.消息循環執行拿到此廣播,回調BroadcastReceiver中的onReceive()方法。app
如今咱們就來實現一個簡單的廣播程序。Android提供了兩種註冊廣播接受者的形式,分別是在程序中動態註冊和在xml中指定。他們之間的區別就是做用的範圍不一樣,程序動態註冊的接收者只在程序運行過程當中有效,而在xml註冊的接收者無論你的程序有沒有啓動有會起做用。首先介紹在程序中動態註冊的方式。ide
public class MainActivity extends Activity { public static final String BROADCAST_ACTION = "com.example.corn"; private BroadcastReceiver mBroadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBroadcastReceiver = new MyBroadcastReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BROADCAST_ACTION); registerReceiver(mBroadcastReceiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mBroadcastReceiver); } class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(null!=intent) Toast.makeText(context, "廣播接收到:", Toast.LENGTH_SHORT).show(); } }
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(); intent.setAction("com.xiazdong"); intent.putExtra("name", "xiazdong"); MainActivity .this.sendBroadcast(intent); } }
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(null!=intent){ String name = intent.getExtras().getString("name"); Toast.makeText(context, "廣播接收到:"+name, Toast.LENGTH_SHORT).show(); } } }
AndroidManiFest.xml 的 <application>中添加this
<receiver android:name=".MyReceiver"> <intent-filter android:priority="1000"> <!-- 設置最高優先級 --> <action android:name="com.xiazdong"/> </intent-filter> </receiver>
案例下載地址:https://github.com/DickyQie/android-four-componentsspa