2025-02-15

和活動、服務及ContentProvider一樣BroadcastReceiver也是Android組件之一,它是可以對客戶端發送的廣播消息作出響應。消息本身是一個Android廣播Intent,廣播消息可以被多個接收程序接收。
在Android系統中,廣播體現在方方面面,例如當開機完成後系統會產生一條廣播,接收到這條廣播就能實現開機啟動服務的功能;當網絡狀態改變時系統會產生一條廣播,接收到這條廣播就能及時地做出提示和保存數據等操作;當電池電量改變時,系統會產生一條廣播,接收到這條廣播就能在電量低時告知用戶及時保存進度,等等。
下面我們就對BroadcastReceiver進行全面的介紹,以瞭解和掌握它的各種功能和用法。
首先,我們來看一下如何發送廣播:
[java]
private void testSendBroadcast(Activity activity){ 
    //create an intent with an action 
    String uniqueActionString = "com.test.broadcast"; 
    Intent intent = new Intent(uniqueActionString); 
    intent.putExtra("message","HelloWoreld!"); 
    //send Broadcast 
    activity.sendBroadcast(intent); 

在上面的代碼中,我們創建瞭一個唯一、特定操作的Intet,並向其中添加瞭一個extra消息,然後調用sendBroadcast()方法,發送瞭一條廣播。
那麼如何接收廣播呢?看代碼
[java]
public class TestReceiver extends BroadcastReceiver{ 
    private static final String tag = "TestReceiver"; 
    public void onReceive(Context context,Intent intent){ 
        Log.i(tag,"intent" + intent); 
        String message = intent.getStringExtra("message"); 
        Log.i(tag,message); 
    } 

創建廣播接收程序非常簡單,隻需擴展BroadcastReceiver類並改寫onReceive()方法。我們可以在接收程序中通過Intent取得廣播發送的具體消息內容。
最後,我們還必須在描述文件中註冊我們編寫的接收程序,否則你將無法收到廣播。
[java]
<receiver android:name=".TestReceiver"> 
    <intent-filter> 
        <action android:name="com.test.broadcast"/> 
        <category android:name="android.intent.category.DEFAULT" /> 
    </intent-filter> 
</receiver> 
這種在描述文件中註冊的方式我們稱之為:靜態方式。這種方式的註冊是常駐型的,也就是說當應用關閉後,如果有廣播信息傳來,TestReceiver也會被系統調用而自動運行,從而接收到廣播消息。
還有一種代碼中實現的動態註冊方式,具體代碼為:
[java]
TestReceiver receiver = new TestReceiver();            
IntentFilter filter = new IntentFilter();   
filter.addAction("com.test.broadcast");            
registerReceiver(receiver, filter);  
registerReceiver是android.content.ContextWrapper類中的方法,Activity和Service都繼承瞭ContextWrapper,所以可以直接調用。在實際應用中,我們在Activity或Service中註冊瞭一個BroadcastReceiver,當這個Activity或Service被銷毀時如果沒有解除註冊,系統會報一個異常,提示我們是否忘記解除註冊瞭。可以通過在onDestory()方法中解除註冊來解決這個問題:
[java]
protected void onDestroy() {   
    super.onDestroy();   
    unregisterReceiver(receiver);   
}  
動態註冊與靜態註冊不同的是:它不是常駐的,一旦程序結束,廣播接收也將結束。
下面我們看一個發送接收廣播的完整例子:
首先來看主活動類:
[java]
public class MainActivity extends Activity 

    private static final String TAG = "MainActivity"; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
    } 
    //創建菜單 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) 
    { 
        super.onCreateOptionsMenu(menu); 
        MenuInflater inflater = getMenuInflater(); 
        inflater.inflate(R.menu.main_menu, menu); 
        return true; 
    } 
    //綁定菜單事件 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) 
    { 
        appendMenuItemText(item); 
        //清空textview 
        if (item.getItemId() == R.id.menu_clear) 
        { 
            this.emptyText(); 
            return true; 
        } 
        //發送廣播 
        if (item.getItemId() == R.id.menu_menu_send_broadcast) 
        { 
            this.testSendBroadcast(); 
            return true; 
        } 
        return true; 
    } 
    private TextView getTextView() 
    { 
        return (TextView)findViewById(R.id.text1); 
    } 
    private void appendMenuItemText(MenuItem item) 
    { 
        String title = item.getTitle().toString(); 
        TextView tv = getTextView(); 
        tv.setText(tv.getText() + "\n" + title); 
    } 
    private void emptyText() 
    { 
        TextView tv = getTextView(); 
        tv.setText(""); 
    } 
    private void testSendBroadcast() 
    { 
        //create an intent with an action 
        String uniqueActionString = "com.test.intents.broadcast"; 
        Intent intent = new Intent(uniqueActionString); 
        intent.putExtra("message","廣播消息發送!"); 
        //send Broadcast 
        this.sendBroadcast(intent); 
    } 

廣播接收器類:
[java]
public class TestReceiver extends BroadcastReceiver{ 
    private static final String tag = "TestReceiver"; 
    public void onReceive(Context context,Intent intent){ 
        Log.i(tag,"intent" + intent); 
        String message = intent.getStringExtra("message"); 
        Log.i(tag,message); 
    } 

下來是佈局文件:
layout/main.xml
[java]
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<TextView   
    android:id="@+id/text1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Your debug will appear here" 
    /> 
</LinearLayout> 
菜單資源文件:
menu/main_menu.xml
[java]
<?xml version="1.0" encoding="utf-8"?> 
<menu xmlns:android="http://schemas.android.com/apk/res/android"> 
    <group android:id="@+id/menuGroup_Main"> 
        <item android:id="@+id/menu_clear" android:title="clear"/> 
        <item android:id="@+id/menu_menu_send_broadcast" android:title="broadcast"/> 
    </group> 
</menu> 
描述文件註冊廣播:
[java]
<application android:icon="@drawable/icon" android:label="@string/app_name"> 
        <activity android:name=".MainActivity" 
                  android:label="@string/app_name"> 
            <intent-filter> 
                <action android:name="android.intent.action.MAIN" /> 
                <category android:name="android.intent.category.LAUNCHER" /> 
            </intent-filter> 
        </activity> 
        <receiver android:name=".TestReceiver"> 
            <intent-filter> 
                <action android:name="com.test.intents.broadcast"></action> 
            </intent-filter> 
        </receiver> 
</application>  

 運行程序,點擊模擬器menu菜單,結果如圖:

點擊broadcast,clear結果如圖:

廣播的概念意味著可能有多個接收程序。我們將再建兩個BroadcastReceiver,並在描述文件中註冊,以測試多個接收者情況。

public class TestReceiver2 extends BroadcastReceiver{ 
    private static final String tag = "TestReceiver2"; 
    public void onReceive(Context context,Intent intent){ 
        Log.i(tag,"intent" + intent); 
        String message = intent.getStringExtra("message"); 
        Log.i(tag,message); 
    } 

同時修改描述文件,註冊關播:
[java]
<receiver android:name=".TestReceiver2"> 
    <intent-filter> 
        <action android:name="com.test.intents.broadcast"></action> 
    </intent-filter> 
</receiver> 
運行程序,打印日志如下:
[java]
04-27 15:03:24.028: INFO/TestReceiver1(1317): intentIntent { act=com.test.intents.broadcast cmp=com.test.broadcast/.TestReceiver (has extras) } 
04-27 15:03:24.038: INFO/TestReceiver1(1317): 廣播消息發送! 
04-27 15:03:24.088: INFO/TestReceiver2(1317): intentIntent { act=com.test.intents.broadcast cmp=com.test.broadcast/.TestReceiver2 (has extras) } 
04-27 15:03:24.088: INFO/TestReceiver2(1317): 廣播消息發送! 
可以知道多個接收器都接收到瞭廣播,並且是依次接收,我們還可以通過在描述文件中修改,從而改變接收順序:
[java]
<receiver android:name=".TestReceiver"> 
    <intent-filter android:priority="999"> 
        <action android:name="com.test.intents.broadcast"></action> 
    </intent-filter> 
</receiver> 
<receiver android:name=".TestReceiver2"> 
    <intent-filter android:priority="1000"> 
        <action android:name="com.test.intents.broadcast"></action> 
    </intent-filter> 
</receiver> 
運行,打印日志如下:
[java]
04-27 15:08:09.778: INFO/TestReceiver2(1470): intentIntent { act=com.test.intents.broadcast cmp=com.test.broadcast/.TestReceiver2 (has extras) } 
04-27 15:08:09.778: INFO/TestReceiver2(1470): 廣播消息發送! 
04-27 15:08:09.888: INFO/TestReceiver1(1470): intentIntent { act=com.test.intents.broadcast cmp=com.test.broadcast/.TestReceiver (has extras) } 
04-27 15:08:09.898: INFO/TestReceiver1(1470): 廣播消息發送! 
可知receiver2先接收,receiver1後接收,這是因為priority值越大,優先級越高。priority值在-1000到1000之

好瞭,關於廣播接收器就暫時介紹到這。

摘自 fwwdn的專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *