0、广播分为静态广播、动态广播、有序广播和无序广播,先从简单的说起;
1、最简单的是静态注册,分为2个步骤:
1.1、创建一个BoradcastReciver的实体子类,实现onReceive()方法;
1.2、在Manifest文件中注册该类及广播事件即可
1
2
3
4
5
| <receiver android:name=".Broadcast">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver> |
<receiver android:name=".Broadcast">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE"/>
</intent-filter>
</receiver>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| package com.yusian.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by Sian on 2017/3/25.
*/
public class Broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "接收到了一个广播", Toast.LENGTH_SHORT).show();
}
} |
package com.yusian.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by Sian on 2017/3/25.
*/
public class Broadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "接收到了一个广播", Toast.LENGTH_SHORT).show();
}
}
还有一类有序广播,有序广播与无序广播在发送广播时调用的方法不一样,有序广播调用的是sendOrderedBroadcast()方法,有序广播会在将接收者中一个一个往下传,类似击鼓传花的模式,每一个接收者对广播的修改都会直接影响后面的接收者
运行结果:
D/SALog: onReceive: CCC–>接收到:初始值
D/SALog: onReceive: BBB–>接收到:C修改了初始值
1、什么是无序广播?无序广播指接收者相互之间独立互不影响;
2、举个栗子,在manifast中注册3个广播接收者,并创建3个BroadcastReciver的实体类;
3、发送广播
Activity
运行结果:
03-25 14:40:38.983 12979-12979/com.yusian.broadcast D/SALog: onReceive: AAA
03-25 14:40:38.993 12979-12979/com.yusian.broadcast D/SALog: onReceive: BBB
03-25 14:40:39.003 12979-12979/com.yusian.broadcast D/SALog: onReceive: CCC
注意:静态广播只要App在运行即可响应,哪怕退到后台也一样;但动态广播则不行,必须前台运行时才能响应;
动态广播可以通过创建一个内部类来实现: