Android BroadcastReceiver

一.註冊方式:

    靜態註冊:靜態註冊是在AndroidManifest.xml文件中配置的html

<receiver android:name=".MyReceiver">  
    <intent-filter>  
        <action android:name="android.intent.action.MY_BROADCAST"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>

    配置了以上信息以後,只要是android.intent.action.MY_BROADCAST這個地址的廣播,MyReceiver都可以接收的到。android

    屬於常駐型的,也就是說當應用關閉後,若是有廣播信息傳來,MyReceiver也會被系統調用而自動運行。spa

    動態註冊:在代碼中動態的指定廣播地址並註冊,一般咱們是在Activity或Service註冊一個廣播。.net

    通常:在onStart中註冊,在onStop/onDestroy中取消unregisterReceivercode

/**
 * 註冊
 */
 IntentFilter intentFilter = new IntentFilter();
 intentFilter.addAction(String);   //爲BroadcastReceiver指定action,使之用於接收同action的廣播
 context.registerReceiver(BroadcastReceiver, intentFilter);
/**
 * 取消
 */
 unregisterReceiver(rhelper);

 

    區別:xml

    1.動態註冊較靜態註冊靈活。htm

    2.當靜態註冊一個BroadcastReceiver時,不論應用程序是啓動與否。均可以接收對應的廣播。     blog

    3.動態註冊的時候,若是不執行unregisterReceiver();方法取消註冊,跟靜態是同樣的。get

    4.可是當動態註冊若是執行unregisterReceiver();方法取消註冊,就不能接收廣播了。it

二.廣播的發送

    指定廣播目標Action:Intent intent = new Intent(actionString);
    而且可經過Intent攜帶消息 :intent.putExtra("msg", "hi,我經過廣播發送消息了");
    發送廣播消息:Context.sendBroadcast(intent )

三.廣播的接收

四.廣播的分類

    1.http://blog.csdn.net/liuhe688/article/details/6955668/

    http://www.cnblogs.com/lwbqqyumidi/p/4168017.html

http://yangguangfu.iteye.com/blog/1063732

http://www.cnblogs.com/jico/articles/1838293.html

相關文章
相關標籤/搜索