---
# System prepended metadata

title: BroadcastReceiver
tags: [介紹]

---

BroadcastReceiver
===
[TOC]

可以想成是ios的 `Notification` 機制。

UI程式碼:
```xml=
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnRegReceiver"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="註冊" />

    <Button
        android:id="@+id/btnSendBroadcast"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="發送廣播" />

    <Button
        android:id="@+id/btnUnregReceiver"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="移除註冊" />
</LinearLayout>
```

## 發送方 (註冊、發送事件)
    
* 設定廣播識別字

```java=
private static final String INTENT_FILTER_ID = "broadcase.test";
```

* 宣告接收方(EX: class Reciever)的類別物件(須繼承`BroadcastReceiver`)，於註冊時建立
```java=
private Reciever mMyReceiver;
```

* 註冊
    * 參考**註冊**按鈕
```java=
BtnRegReceiver = (Button)findViewById(R.id.btnRegReceiver);
BtnRegReceiver.setOnClickListener(btnRegReceiverOnClickLis);
```

* 發送廣播
    * 參考**發送廣播**按鈕
```java=
BtnSendBroadcast = (Button)findViewById(R.id.btnSendBroadcast);
BtnSendBroadcast.setOnClickListener(btnSendBroadcastOnClickLis);
```

* 取消註冊廣播
    * 參考**移除註冊**按鈕
```java=
BtnUnregReceiver = (Button)findViewById(R.id.btnUnregReceiver);
BtnUnregReceiver.setOnClickListener(btnUnregReceiverOnClickLis);
```

程式碼：
```java=

public class MainActivity extends AppCompatActivity {

    private static final String INTENT_FILTER_ID = "broadcase.test";

    private Reciever mMyReceiver; //自訂一個繼承 BroadcastReceiver 的類別

    private Button BtnRegReceiver;      //註冊廣播
    private Button BtnUnregReceiver;    //撤銷廣播
    private Button BtnSendBroadcast;    //發送廣播

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BtnRegReceiver = (Button)findViewById(R.id.btnRegReceiver);
        BtnUnregReceiver = (Button)findViewById(R.id.btnUnregReceiver);
        BtnSendBroadcast = (Button)findViewById(R.id.btnSendBroadcast);

        BtnRegReceiver.setOnClickListener(btnRegReceiverOnClickLis);
        BtnUnregReceiver.setOnClickListener(btnUnregReceiverOnClickLis);
        BtnSendBroadcast.setOnClickListener(btnSendBroadcastOnClickLis);
    }

    private Button.OnClickListener btnRegReceiverOnClickLis = new Button.OnClickListener() {
        public void onClick(View v) {
            if (mMyReceiver == null) {
                IntentFilter itFilter = new IntentFilter(INTENT_FILTER_ID);

                // 同上面用法
                // Intent itFilter = new IntentFilter();
                // itFilter.addAction(INTENT_FILTER_ID);

                mMyReceiver = new Reciever();
                registerReceiver(mMyReceiver, itFilter);    //註冊廣播接收器
                Log.d("debug", "註冊成功");
            } else {
                Log.d("debug", "您已註冊過");
            }
        }
    };

    private Button.OnClickListener btnUnregReceiverOnClickLis = new Button.OnClickListener() {
        public void onClick(View v) {
            if (mMyReceiver != null) {
                unregisterReceiver(mMyReceiver);    // 撤銷廣播接收器
                mMyReceiver = null;
                Log.d("debug", "移除成功");
            } else {
                Log.d("debug", "您已移除，請重新註冊");
            }
        }
    };

    private Button.OnClickListener btnSendBroadcastOnClickLis = new Button.OnClickListener() {
        public void onClick(View v) {
            Intent it = new Intent(INTENT_FILTER_ID); // 設定廣播識別碼
            it.putExtra("sender_name", "Broadcast test"); // 設定廣播夾帶參數以key-value型式
            sendBroadcast(it); // 發送廣播訊息
        }
    };
}
```

## 接收方 (接收、處理事件)

* 必須繼承 **`BroadcastReceiver`** 並實作其方法

程式碼：

```java=
public class Reciever extends BroadcastReceiver {

    Reciever() {

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String name = intent.getStringExtra("sender_name");
        Log.d("debug", "收到訊息: " + name);
    }
}

```

## Ref.

[《Android》『BroadcastReceiver』- 廣播接收器的基本用法](https://xnfood.com.tw/android-broadcastreceiver/#skill_01)
[[Android] BroadcastReceiver - 廣播接收器](http://aiur3908.blogspot.com/2015/05/android-broadcastreceiver.html)

###### tags: `介紹`