Broadcast

2019-02-27  本文已影响0人  _Rice_

特点:是一个典型的发布-订阅模式,发送方不关心接收方是否接到数据,也不关系接收方如何处理数据

注意:

分类:普通广播、有序广播、本地广播、sticky广播

普通广播

优点:

缺点:

广播接受者定义:

public class HelloBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = HelloBroadcastReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG,"hello");
    }
}

当接受到广播时,会调用onReceive()方法。

广播接受者声明方式:

1、清单声明

<receiver
    android:name=".components.broadcast.HelloBroadcastReceiver"
    android:exported="false">
    <!--intent过滤器指定接收者订阅的广播操作。-->
    <intent-filter>
        <action android:name="hello"/>

    </intent-filter>
</receiver>

exported为false表示接收方不接受来自应用外的广播

2、上下文注册

registerReceiver(new HelloBroadcastReceiver(),new IntentFilter("hello"));

取消注册

unregisterReceiver(android.content.BroadcastReceiver)

发送广播:

sendBroadcast(new Intent("hello"));

有序广播

优点:

显然有序广播优化了普通广播的缺点

设置广播优先级

mHelloBroadcastReceiver = new HelloBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter("hello");
intentFilter.setPriority(50);
registerReceiver(mHelloBroadcastReceiver,intentFilter);

发送广播

sendOrderedBroadcast(new Intent("hello"),null);

讲解:

@Override
public void sendOrderedBroadcast(Intent intent,
            String receiverPermission) {
    mBase.sendOrderedBroadcast(intent, receiverPermission);
    }

receiverPermission这个参数是接受权限,接受应用必须请求对应权限

本地广播

上述的广播都是全局的,如果不需要向应用程序外部的组件发起广播,可以使用本地广播,提高效率。

LocalBroadcastManager可以实现限于应用内的广播

//注册广播
LocalBroadcastManager.getInstance(this).registerReceiver(@NonNull BroadcastReceiver receiver,
            @NonNull IntentFilter filter)

//注销广播
LocalBroadcastManager.getInstance(this).unregisterReceiver(@NonNull BroadcastReceiver receiver)

//发送异步广播
LocalBroadcastManager.getInstance(this).sendBroadcast(@NonNull Intent intent)

//发送本地广播
LocalBroadcastManager.getInstance(this).sendBroadcastSync(@NonNull Intent intent)

sticky广播

通过Context.sendStickyBroadcast(Intent intent)发送。发送粘性广播还需要BROADCAST_STICKY权限:

<uses-permission android:name="android.permission.BROADCAST_STICKY"/>

特点:

参考:https://developer.android.com/guide/components/broadcasts

上一篇 下一篇

猜你喜欢

热点阅读