android四大組件之BroadcastReceiver,broadcastreceiver

來源:互聯網
上載者:User

android四大組件之BroadcastReceiver,broadcastreceiver

今天回頭看了自己之前學習的筆記,小結了一下BroadcastReceiver,供剛入門的朋友複習和參考。

BroadcastReceiver是android系統一個全域的監聽器,可實現不同組件之間的通訊。

建立自己的廣播類

package com.example.yummyhttputil; import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.os.IBinder; public class MyBoradcastReceiver extends BroadcastReceiver {     /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub     }     @Override    public void onReceive(Context context, Intent intent) {        // TODO Auto-generated method stub             }     @Override    public IBinder peekService(Context myContext, Intent service) {        // TODO Auto-generated method stub        return super.peekService(myContext, service);    } }


註冊廣播        靜態註冊
<receiver android:name=".MyBoradcastReceiver ">              <intent-filter>                  <action android:name="android.intent.action.MYBROADCAST_RECEIVER"/>                  <category android:name="android.intent.category.DEFAULT" />              </intent-filter>  </receiver>  
配置了以上資訊之後,只要是android.intent.action.MY_BROADCAST這個地址的廣播,MyReceiver都能夠接收的到。注意,這種方式的註冊是常駐型的,也就是說當應用關閉後,如果有廣播資訊傳來,MyReceiver也會被系統調用而自動運行。
動態註冊
MyBoradcastReceiver receiver = new MyBoradcastReceiver ();           IntentFilter filter = new IntentFilter();  filter.addAction("android.intent.action.MYBROADCAST_RECEIVER");        registerReceiver(receiver, filter);  
注意,registerReceiver是android.content.ContextWrapper類中的方法,Activity和Service都繼承了ContextWrapper,所以可以直接調用。在實際應用中,我們在Activity或Service中註冊了一個BroadcastReceiver,當這個Activity或Service被銷毀時如果沒有解除註冊,系統會報一個異常,提示我們是否忘記解除註冊了。所以,記得在特定的地方執行解除註冊操作:
@Override  protected void onDestroy() {      super.onDestroy();      unregisterReceiver(receiver);  }  


發送廣播
public void send(View view) {      Intent intent = new Intent("android.intent.action.MYBROADCAST_RECEIVER");      intent.putExtra("msg", "hello yummylau!");      sendBroadcast(intent);  } 


廣播的種類普通廣播(Normal Broadcast)普通廣播對於多個接收者來說是完全非同步,通常每個接收者都無需等待即可以接收到廣播,接收者相互之間不會有影響。對於這種廣播,接收者無法終止廣播,即無法阻止其他接收者的接收動作。
有序廣播(Ordered Broadcast)有序廣播比較特殊,它每次只發送到優先順序較高的接收者那裡,然後由優先順序高的接受者再傳播到優先順序低的接收者那裡,優先順序高的接收者有能力終止這個廣播。
設定三個廣播接受類,通過設定優先權來決定誰先消費該廣播
<receiver android:name=".FirstReceiver">      <intent-filter android:priority="1000">          <action android:name="android.intent.action.MYBROADCAST_RECEIVER"/>          <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.MYBROADCAST_RECEIVER"/>          <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.MYBROADCAST_RECEIVER"/>          <category android:name="android.intent.category.DEFAULT" />      </intent-filter>  </receiver>  

三個接收者的<intent-filter>多了一個android:priority屬性,並且依次減小。這個屬性的範圍在-1000到1000,數值越大,優先順序越高。
發送有序廣播

public void send(View view) {      Intent intent = new Intent("android.intent.action.MYBROADCAST_RECEIVER");      intent.putExtra("msg", "hello yummylau!");      sendOrderedBroadcast(intent, "scott.permission.MY_BROADCAST_PERMISSION");  } 

注意,使用sendOrderedBroadcast方法發送有序廣播時,需要一個許可權參數,如果為null則表示不要求接收者聲明指定的許可權,如果不為null,則表示接收者若要接收此廣播,需聲明指定許可權。這樣做是從安全形度考慮的,例如系統的簡訊就是有序廣播的形式,一個應用可能是具有攔截垃圾簡訊的功能,當簡訊到來時它可以先接受到簡訊廣播,必要時終止廣播傳遞,這樣的軟體就必須聲明接收簡訊的許可權。
所以我們在AndroidMainfest.xml中定義一個許可權:
<permission android:protectionLevel="normal"              android:name="scott.permission.MYBROADCAST_RECEIVER_PERMISSION" /> 
然後聲明這個許可權
<uses-permission android:name="scott.permission.MYBROADCAST_RECEIVER_PERMISSION" />  
如果第一個廣播需要添加訊息給第二個廣播,可以在onReceive()中添加
Bundle bundle = new Bundle();bundle.putString("addString","我是添加的訊息");setResultExtras(bundle);
而第二個廣播類中取出
Bundle bundle = getResultExtras(true);String add = bundle.getString("addString");
取消繼續傳遞廣播
abortBroadcast();  












聯繫我們

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