普通广播
创建一个广播接收器
class broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Ma", "广播");
}}
新建一个广播发送器
Intent intent = new Intent();
intent.setAction("com.xiazdong");
sendBroadcast(intent);
创建一个过滤器,控制要接收的内容
IntentFilter filter=new IntentFilter();
filter.addAction("com.xiazdong");
打开广播接收器
registerReceiver(new broadcast , filter);
线性广播
创建两个广播接收器
class broadcast01 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Ma", "第一个广播");
abortBroadcast();
}}
class broadcast02 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Ma", "第二个广播");
}}
在AndroidManifest.xml中注册两个广播接收器
<receiver android:name=".broadcast01" >
<intent-filter android:priority="20" > <!-- 控制优先权限高低,优先级数值为-1000——1000,1000是最高优先权--->
<action android:name="com.example.broadcast.broadcast"/>
</intent-filter>
</receiver>
<receiver android:name=".broadcast02" >
<intent-filter android:priority="20" >
<action android:name="com.example.broadcast.broadcast"/>
</intent-filter>
</receiver>
新建一个广播发送器
Intent intent = new Intent();
intent.setAction("com.example.broadcast.broadcast");
sendOrderedBroadcast(intent, null);
粘滞性广播
创建一个广播接收器
class broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Ma", "广播");
}}
新建一个广播发送器
Intent intent = new Intent();
intent.setAction("com.xiazdong");
sendStickyBroadcast(intent);
创建一个过滤器,控制要接收的内容
IntentFilter filter=new IntentFilter();
filter.addAction("com.xiazdong");
打开广播接收器
registerReceiver(new broadcast , filter);
<!-- 想发送粘性消息的时候必须在配置文件里面获取权限: -->
<uses-permission android:name="android.permission.BROADCAST_STICKY" />