Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 廣播實作三步驟:在 Activity 中註冊並發送自訂廣播

編輯:關於 Android 程式設計

廣播(Broadcast)是 Android 元件之間解耦溝通的常用手段。本文用一個最小範例,說明如何在 Activity 中完成「定義接收器 → 註冊 → 發送」這一整條流程。

第一步:定義 BroadcastReceiver

繼承 BroadcastReceiver 並覆寫 onReceive(),在裡面比對 action,決定要做什麼:

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ACTION_NAME)) {
            Toast.makeText(Test.this, "處理 action 名字相對應的廣播", 200).show();
        }
    }
};

第二步:註冊廣播

建立 IntentFilter,把感興趣的 action 加進去,再呼叫 registerReceiver():

public void registerBoradcastReceiver() {
    IntentFilter myIntentFilter = new IntentFilter();
    myIntentFilter.addAction(ACTION_NAME);
    // 註冊廣播
    registerReceiver(mBroadcastReceiver, myIntentFilter);
}

第三步:發送廣播

用 Intent 帶上 action,需要的話再用 putExtra() 塞入要傳遞的資料,最後 sendBroadcast():

mBtnMsgEvent.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent mIntent = new Intent(ACTION_NAME);
        mIntent.putExtra("yaner", "發送廣播,相當於在這裡傳送數據");
        // 發送廣播
        sendBroadcast(mIntent);
    }
});

完整程式碼

package my.yaner;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Test extends Activity {
    private final String ACTION_NAME = "yaner";
    private Button mBtnMsgEvent = null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 註冊廣播
        registerBoradcastReceiver();

        LinearLayout mLinearLayout = new LinearLayout(this);
        mBtnMsgEvent = new Button(this);
        mBtnMsgEvent.setText("發送廣播");
        mLinearLayout.addView(mBtnMsgEvent);
        setContentView(mLinearLayout);

        mBtnMsgEvent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(ACTION_NAME);
                mIntent.putExtra("yaner", "發送廣播,相當於在這裡傳送數據");
                sendBroadcast(mIntent);
            }
        });
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_NAME)) {
                Toast.makeText(Test.this, "處理 action 名字相對應的廣播", 200).show();
            }
        }
    };

    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTION_NAME);
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
}

幾個實務提醒:動態註冊的廣播記得在 onDestroy() 中呼叫 unregisterReceiver() 反註冊,否則容易造成記憶體洩漏;靜態廣播則要寫進 AndroidManifest.xml。另外從 Android 8.0 起,大部分隱含 Intent 的靜態廣播已被限制,自訂 action 建議一律走動態註冊或改用其他元件溝通機制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved