android BroadcastReciver初步研究–註冊部分

來源:互聯網
上載者:User

在Android中,Broadcast是一種廣泛運用的在應用程式之間傳輸資訊的機制。而BroadcastReceiver是對發送出來的 Broadcast進行過濾接受並響應的一類組件。

下面將詳細的闡述如何發送Broadcast和使用BroadcastReceiver過濾接收的過程:

  首先在需要發送資訊的地方,把要發送的資訊和用於過濾的資訊(如Action、Category)裝入一個Intent對象,然後通過調用 sendOrderBroadcast()或sendStickyBroadcast()方法,把 Intent對象以廣播方式發送出去。

  當Intent發送以後,所有已經註冊的BroadcastReceiver會檢查註冊時的IntentFilter是否與發送的Intent相匹配,若匹配則就會調用BroadcastReceiver的onReceive()方法。所以當我們定義一個BroadcastReceiver的時候,都需要實現onReceive()方法。

  註冊BroadcastReceiver有兩種方式:

  靜態註冊:在AndroidManifest.xml中用標籤生命註冊,並在標籤內用標籤設定過濾器。

  

<receiver android:name="myRecevice">    //繼承BroadcastReceiver,重寫onReceiver方法    <intent-filter>          <action android:name="com.dragon.net"></action> //使用過濾器,接收指定action廣播      </intent-filter>  </receiver> 

  動態註冊:

 

 IntentFilter intentFilter = new IntentFilter();  intentFilter.addAction(String);   //為BroadcastReceiver指定action,使之用於接收同action的廣播      registerReceiver(BroadcastReceiver,intentFilter);
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.