盒子
盒子
文章目录
  1. 接收者
    1. 广播监听注册
  2. 发送者
    1. 广播类型
  3. onReceive中的Context

Broadcast的使用

Android广播机制采用观察者模式

接收者

BroadcastReceiver

该类为广播接收器类,示例代码为:

1
2
3
4
5
6
7
public class MyBroadcastReceiver extends BroadcastReceiver {
public static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"onReceive");
}
}

当发送者发送广播时,onReceive方法会被触发执行

广播监听注册

  • 静态注册
  • 1
    2
    3
    4
    5
    6
    7
    8
    <receiver android:name=".MyBroadcastReceiver" >
    <intent-filter>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
    <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
    </receiver>

    action android:name的值指定的是触发条件:

    android.net.conn.CONNECTIVITY_CHANGE

    指的是网络改变

    android.intent.action.BOOT_COMPLETED

    指的是系统启动

  • 动态注册
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public class MainActivity extends Activity {
    public static final String BROADCAST_ACTION = "grooters.github.io";
    private BroadcastReceiver mBroadcastReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mBroadcastReceiver = new MyBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    //添加触发条件
    intentFilter.addAction(BROADCAST_ACTION);
    registerReceiver(mBroadcastReceiver, intentFilter);
    }
    @Override
    protected void onDestroy() {
    super.onDestroy();
    //注销该监听器
    unregisterReceiver(mBroadcastReceiver);
    }
    }

    当发送者发送的广播的Action为grooters.github.io时便会触发该监听器

    发送者

    1
    2
    3
    4
    5
    Intent intent=new Intent();
    intent.setAction(BROADCAST_ACTION);
    //可在监听方法onReceiver的intent参数中取出数据
    intent.putExtra("data","Hello");
    sendBroadcast(intent);

    广播类型

  • 普通广播
  • 系统广播
  • 提供多个已存在的系统动作Action,如开机自启,网络改变,电量不足

  • 有序广播
  • 有顺序地接收不同的广播,顺序取决于priority的值,越大就越前

    1
    <intent-filter android:priority="1">

  • 本地广播
  • 只有本app能接收到该广播

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //接收者
    LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
    localBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);
    localBroadcastManager.unregisterReceiver(mBroadcastReceiver);

    //发送者
    Intent intent = new Intent();
    intent.setAction(BROADCAST_ACTION);
    intent.putExtra("data", "Hello");
    localBroadcastManager.sendBroadcast(intent);

    onReceive中的Context

  • 镜头注册
  • context 具体指的是 ReceiverRestrictedContext

  • 动态注册
  • context 具体指的是 Activity Context

  • 本地广播
  • context 具体指的是 Application Context

    支持一下
    扫一扫,支持Grooter
    • 微信扫一扫
    • 支付宝扫一扫