android_BroadcastReceiver 廣播機制,android廣播機制

來源:互聯網
上載者:User

android_BroadcastReceiver 廣播機制,android廣播機制
廣播接收者( BroadcastReceiver )顧名思義,它就是用來接收來自系統和應用中的廣播。它用於接收廣播 Intent ,廣播 Intent 的發送是通過調用Context.sendBroadcast() 、 Context.sendOrderedBroadcast() 來實現的。通常一個廣播 Intent 可以被訂閱了此Intent 的多個廣播接收者所接收。例如當開機完成後系統會產生一條廣播,接收到這條廣播就能實現開機啟動服務的功能;當網路狀態改變時系統會產生一條廣播,接收到這條廣播就能及時地做出提示和儲存資料等操作;當電池電量改變時,系統會產生一條廣播,接收到這條廣播就能在電量低時告知使用者及時儲存進度等。
1、建立BroadcastReceiver對象,需要繼承android.content.BroadcastReceiver,並實現其onReceive方法。

public class MyReceiver extends BroadcastReceiver {private static final String TAG = "MyReceiver";@Overridepublic void onReceive(Context arg0, Intent intent) {String msg = intent.getStringExtra("msg");Log.i(TAG, msg);}}
在onReceive方法內,可以擷取隨廣播而來的Intent中的資料,並進行處理。
2、建立好BroadcastReceiver之後,還需對其進行註冊。
- 靜態註冊:在AndroidManifest.xml檔案中配置
    <receiver android:name=".MyReceiver" >        <intent-filter>            <action android:name="android.intent.action.MY_BROADCAST" />        </intent-filter>    </receiver>
配置好之後,只要是android.intent.action.MY_BROADCAST這個地址的廣播,MyReceiver都能夠接收的到。注意,這種方式的註冊是常駐型的,也就是說當應用關閉後,如果有廣播資訊傳來,MyReceiver也會被系統調用而自動運行。
-動態註冊:在代碼中動態指定廣播位址並註冊,通常我們是在Activity或Service註冊一個廣播。
class BroadcastReceiverListener implements OnClickListener{public void onClick(View arg0) {// 動態註冊// 產生一個BroadcastReceiver對象myReceiver = new MyReceiver();// 產生一個IntentFilter對象IntentFilter filter = new IntentFilter();// 為IntentFilter添加一個actionfilter.addAction("android.intent.action.MY_BROADCAST");// 將broadcastReceiver對象註冊到系統當中registerReceiver(myReceiver, filter);}}
registerReceiver是android.content.ContextWrapper類中的方法,Activity和Service都繼承了ContextWrapper,所以可以直接調用。在實際應用中,我們在Activity或Service中註冊了一個BroadcastReceiver,當這個Activity或Service被銷毀時如果沒有解除註冊,系統會報一個異常,提示我們是否忘記解除註冊了。所以,記得在特定的地方執行解除註冊操作:
@Override  protected void onDestroy() {      super.onDestroy();      unregisterReceiver(myReceiver);  } 
執行這樣行代碼就可以解決問題了。注意,這種註冊方式與靜態註冊相反,不是常駐型的,也就是說廣播會跟隨程式的生命週期。
3、註冊好Broadcastreceiver之後,就可以使用它了。
class BroadcastReceiverListener implements OnClickListener{public void onClick(View v) {Intent intent = new Intent("android.intent.action.MY_BROADCAST");intent.putExtra("msg", "hello world!");// intent.setAction("android.intent.action.MY_BROADCAST");sendBroadcast(intent);}}
sendBroadcast也是android.content.ContextWrapper類中的方法,它可以將一個指定地址和參數資訊的Intent對象以廣播的形式發送出去。

點擊按鈕,就可以把廣播發送出去,並且被MyReceiver接收到。

>>>上面的例子只是一個接收者來接收廣播,如果有多個接收者都註冊了相同的廣播位址,又會是什麼情況呢,能同時接收到同一條廣播嗎,相互之間會不會有幹擾呢?這就涉及到普通廣播和有序廣播的概念了。

普通廣播(Normal Broadcast)
普通廣播對於多個接收者來說是完全非同步,通常每個接收者都無需等待即可以接收到廣播,接收者相互之間不會有影響。對於這種廣播,接收者無法終止廣播,即無法阻止其他接收者的接收動作。
建立三個BroadcastReceiver,FirstReceiver、SecondReceiver和ThirdReceiver,示範一下這個過程。
public class FirstReceiver extends BroadcastReceiver {            private static final String TAG = "NormalBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = intent.getStringExtra("msg");          Log.i(TAG, "FirstReceiver: " + msg);      } }
public class SecondReceiver extends BroadcastReceiver {            private static final String TAG = "NormalBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = intent.getStringExtra("msg");          Log.i(TAG, "SecondReceiver: " + msg);      }} 
public class ThirdReceiver extends BroadcastReceiver {            private static final String TAG = "NormalBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = intent.getStringExtra("msg");          Log.i(TAG, "ThirdReceiver: " + msg);      }}  
再次點擊發送按鈕,發送一條廣播,控制台列印:

三個接收者都接收到這條廣播,如果在三個接收者的onReceive方法的最後一行添加代碼,試圖終止廣播:
abortBroadcast();

再次點擊發送按鈕,控制台中三個接收者仍然都列印了自己的日誌,表明接收者並不能終止廣播。

有序廣播(Ordered Broadcast)
有序廣播比較特殊,它每次只發送到優先順序較高的接收者那裡,然後由優先順序高的接受者再傳播到優先順序低的接收者那裡,優先順序高的接收者有能力終止這個廣播。
還是用三個BroadcastReceiver來舉例。

public class FirstReceiver extends BroadcastReceiver {            private static final String TAG = "OrderedBroadcast";          @Override    public void onReceive(Context context, Intent intent) {        String msg = intent.getStringExtra("msg");        Log.i(TAG, "FirstReceiver: " + msg);                Bundle bundle = new Bundle();        bundle.putString("msg", msg + "@FirstReceiver");        setResultExtras(bundle);    }} 
public class SecondReceiver extends BroadcastReceiver {            private static final String TAG = "OrderedBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = getResultExtras(true).getString("msg");          Log.i(TAG, "SecondReceiver: " + msg);                    Bundle bundle = new Bundle();          bundle.putString("msg", msg + "@SecondReceiver");          setResultExtras(bundle);      }}
public class ThirdReceiver extends BroadcastReceiver {            private static final String TAG = "OrderedBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = getResultExtras(true).getString("msg");          Log.i(TAG, "ThirdReceiver: " + msg);      }}
在FirstReceiver和SecondReceiver中最後都使用了setResultExtras方法將一個Bundle對象設定為結果集對象,傳遞到下一個接收者那裡,這樣以來,優先順序低的接收者可以用getResultExtras擷取到最新的經過處理的資訊集合。
然後,我們需要為三個接收者註冊廣播位址,我們修改一下AndroidMainfest.xml檔案:
<receiver android:name=".FirstReceiver">      <intent-filter android:priority="1000">          <action android:name="android.intent.action.MY_BROADCAST"/>          <category android:name="android.intent.category.DEFAULT" />      </intent-filter>  </receiver>  <receiver android:name=".SecondReceiver">      <intent-filter android:priority="999">          <action android:name="android.intent.action.MY_BROADCAST"/>          <category android:name="android.intent.category.DEFAULT" />      </intent-filter>  </receiver>  <receiver android:name=".ThirdReceiver">      <intent-filter android:priority="998">          <action android:name="android.intent.action.MY_BROADCAST"/>          <category android:name="android.intent.category.DEFAULT" />      </intent-filter>  </receiver> 
現在這三個接收者的<intent-filter>多了一個android:priority屬性,並且依次減小。這個屬性的範圍在-1000到1000,數值越大,優先順序越高。
然後修改一下發送廣播的代碼:
class BroadcastReceiverListener implements OnClickListener{public void onClick(View arg0) {Intent intent = new Intent("android.intent.action.MY_BROADCAST");intent.putExtra("msg", "hello world!");// intent.setAction("android.intent.action.MY_BROADCAST");// sendBroadcast(intent);sendOrderedBroadcast(intent, "scott.permission.MY_BROADCAST_PERMISSION");}}
使用sendOrderedBroadcast方法發送有序廣播時,需要一個許可權參數,如果為null則表示不要求接收者聲明指定的許可權,如果不為null,則表示接收者若要接收此廣播,需聲明指定許可權。這樣做是從安全形度考慮的,例如系統的簡訊就是有序廣播的形式,一個應用可能是具有攔截垃圾簡訊的功能,當簡訊到來時它可以先接受到簡訊廣播,必要時終止廣播傳遞,這樣的軟體就必須聲明接收簡訊的許可權。
所以在AndroidMainfest.xml中定義一個許可權:
<permission android:protectionLevel="normal" android:name="scott.permission.MY_BROADCAST_PERMISSION" />  
然後聲明使用了此許可權:
<uses-permission android:name="scott.permission.MY_BROADCAST_PERMISSION" />  
然後我們點擊發送按鈕發送一條廣播,控制台列印如下:

我們看到接收是按照順序的,第一個和第二個都在結果集中加入了自己的標記,並且向優先順序低的接收者傳遞下去。

既然是順序傳遞,試著終止這種傳遞,看一看效果如何,我們修改FirstReceiver的代碼,在onReceive的最後一行添加abortBroadcast(); 再次運行程式,此次,只有第一個接收者執行了,其它兩個都沒能執行,因為廣播被第一個接收者終止了。

參考:
http://blog.csdn.net/liuhe688/article/details/6955668

Android聲明和使用許可權 http://blog.csdn.net/liuhe688/article/details/6417983


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.