Android 广播机制(Broadcast)

2019-07-08  本文已影响0人  风之化身呀

1、基本概念

2、基本用法

2.1、动态注册

1、通过 IntentFilter 确定监听何种类型的广播

private IntentFilter intentFilter = new IntentFilter();\
intentFileter.addAction("android.net.conn.CONNECTIVITY_CHANGE")

2、初始化一个继承 BroadcastReceiver 类的实例

class NetworkChangeReceiver extends BroadcastRecerver {
    @override
    public void onReceive(Context context,Intent intent){
        Toast.makeText(context,"network change",Toast.LENGTH_SHORT).show();
    }
}

3、通过 registerReceiver 绑定两者

registerReceiver(networkChangeReceiver,intentFilter)

4、销毁时 unRegisterReceiver 解除绑定

unRegisterReceiver (networkChangeReceiver)

2.2、静态注册

1、在 AndroidManifest.xml 中写一个 receiver 标签,表明目的。注意需要申明权限

      <uses-permission android:name="android.permission.RECEIVE_BOOT_STATE" />
      <receiver 
            android:name=".BootReceiver"
            android:enabled="true"
            android:exported="true"
            >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter>
        </receiver>

2、写一个类BootReceiver 继承 BroadcastRecerver

class BootReceiver extends BroadcastRecerver {
    @override
    public void onReceive(Context context,Intent intent){
        Toast.makeText(context,"boot",Toast.LENGTH_SHORT).show();
    }
}

2.3、自定义广播(静态注册模式)

1、在 AndroidManifest.xml 中写一个 receiver 标签,表明目的。注意需要申明权限
2、调用 sendBroadcast(intent) 方式发送自定义广播

Intent intent = new Intent("com.example.xxx.MY_BROADCAST")
sendBroadcast(intent)

3、若要发送有序广播,则调用 sendOrderedBroadcast。同时可以在 AndroidManifest.xml 中给 intent-filter 设置 priority 指定优先级,若不想继续传播,则可以调用 abortBroadcast()

Intent intent = new Intent("com.example.xxx.MY_BROADCAST")
sendOrderedBroadcast(intent,null)

2.4、使用本地广播 LocalBroadcastManger

以上都是全局广播,任何应用都可监听,存在安全性问题,可用 LocalBroadcastManger 使用本地广播解决该问题。

private LocalBroadcastManger  localBroadcastManger 
localBroadcastManger = LocalBroadcastManger.getInstance(this)

Intent intent = new Intent("com.example.xxx.MY_BROADCAST")
localBroadcastManger.sendBroadcast(intent)

private IntentFilter intentFilter = new IntentFilter();\
intentFileter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
localBroadcastManger.registerReceiver(networkChangeReceiver,intentFilter)
上一篇下一篇

猜你喜欢

热点阅读