回顾一下安卓Broadcast

引言

我首先想到的是周杰伦的一首歌,“训导处报告训导处报告,三年二班周杰伦,马上到训导处来”,广播里面这么一呼叫,估计周杰伦就得屁颠屁颠的去被训了,分析整个事情,首先广播这玩意儿一呼叫,全校同学都听得见,然后再根据姓名,进行匹配,周杰伦听到自己的名字,就去做响应的事情了。安卓的广播机制类似,也是在安卓系统中去发送一条广播,然后注册的广播接受者监听到了广播后,就回去匹配,是否是在叫自己,如果发现是自己,那么就去做相应的事情,广播不难,但是也有必要回顾总结一下,好记性不如烂笔头,方便以后查阅。

广播监听者BroadcastReceiver

BroadcastReceiver就是像特工一样,特工监听某个频段,而BroadcastReceiver监听安卓系统的信息,一旦符合,便启动,那么首先来看看什么是BroadcastReceiver。

BroadcastReceiver基本知识


BroadcastReceiver,广播接收者,用来接收系统和应用的广播,并做出相应的处理,如电量过低时提示用户充电等;
BroadcastReceiver 是 Android 的四大组件之一,分为 普通广播、有序广播、粘性广播;
BroadcastReceiver 的使用步骤:
1). 自定义一个类,继承自 BroadcastReceiver,并重写 onReceive() 方法,在该方法中对接收到的广播进行相应的处理;
2). 注册广播地址:分为静态注册 (在 AndroidManifest.xml 中注册) 和动态注册 (在代码中注册)
3). 发送广播:普通广播 sendBroadcast()、有序广播 sendOrderedBroadcast()、粘性广播 sendStickyBroadcast()

普通广播 (Normal Broadcast)

普通广播对于接收者来说是异步的,每个接收者都可以接收到广播,接收者不会相互干扰,也因此,接收者无法终止广播。
BroadcastReceiver可以静态注册,也可以代码动态注册

让我们首先来写一个最简单的静态注册的例子吧~

静态广播注册

首先是布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/send_broadcast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:paddingBottom="10dp"
android:background="#88888888"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:text="发送一个广播" />
</RelativeLayout>

然后是Activity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private View sendBroadcast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBroadcast = findViewById(R.id.send_broadcast);
}
@Override
protected void onStart() {
super.onStart();
sendBroadcast.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_broadcast) {
// 1. 创建一个 Intent 对象;
Intent intent = new Intent();
// 2. 设置 Action;
intent.setAction("example.broadcast.com.broadcastexample.ACTION_BROADCAST_SEND");
// 3. 发送普通广播
sendBroadcast(intent);
}
}
}

然后是自定义的广播:

1
2
3
4
5
6
7
8
9
public class ExampleBroadcastReceiver extends BroadcastReceiver {
public static final String TAG = ExampleBroadcastReceiver.class.getCanonicalName();
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "接收到一条来自" + intent.getAction() + "的广播请求");
}
}

最后我们需要在AndroidManifest中去声明这个广播,并且给它设置intent-filter,

1
2
3
4
5
<receiver android:name=".broadcast.ExampleBroadcastReceiver">
<intent-filter>
<action android:name="example.broadcast.com.broadcastexample.ACTION_BROADCAST_SEND" />
</intent-filter>
</receiver>

运行程序,最后长这样:

点击按钮,发送一条广播,会看到命令行多了一条记录:

1
ExampleBroadcastReceiver: 接收到一条来自example.broadcast.com.broadcastexample.ACTION_BROADCAST_SEND的广播请求

多次点击,会有多条信息打印出来,就是这么简单,发送一条广播,BroadcastReceiver接收到匹配自己的ACTION的广播,就进行相应的事件处理。

动态广播注册

动态广播无需在AndroidManifest.xml中声明,所以去掉上面的声明然后主要是在Activity中进行注册,并在onDestroy的时候解注册:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private View sendBroadcast;
private ExampleBroadcastReceiver exampleBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBroadcast = findViewById(R.id.send_broadcast);
exampleBroadcastReceiver = new ExampleBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("example.broadcast.com.broadcastexample.ACTION_BROADCAST_SEND");
registerReceiver(exampleBroadcastReceiver,intentFilter);
}
@Override
protected void onStart() {
super.onStart();
sendBroadcast.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_broadcast) {
// 1. 创建一个 Intent 对象;
Intent intent = new Intent();
// 2. 设置 Action;
intent.setAction("example.broadcast.com.broadcastexample.ACTION_BROADCAST_SEND");
// 3. 发送普通广播
sendBroadcast(intent);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(exampleBroadcastReceiver);
}
}

好了,界面还是和上面一样,点击的结果也一摸一样,那么它们之间有什么区别吗?主要有以下这些方面:

1). 静态注册是在 AndroidManifest.xml 中注册,动态注册是在代码中注册;
2). 静态注册是常驻型的,即使应用没有启动时也能接收广播;而动态注册的广播的生命周期受到其用来注册的 Activity 或 Service 的影响,当其用来注册的 Activity 或 Service 关闭时其广播也就失效了;
3). 动态注册的广播在 Activity 或 Service 被销毁时必须解除注册,而静态注册的关闭则不用;
4). 动态注册的优先级要比静态注册的优先级高。

有序广播 (Ordered Broadcast)

有序广播每次只将广播发送给优先级较高的接收者,优先级高的接收者可以决定是将广播发送给优先级低的接收者,还是终止这个广播。

我们接下来自定义三个 BroadcastReceiver,并设置它们的优先级别依次降低,然后发送一条广播,看看效果如何。
重新建个OrderBroadcastActivity,布局还是和原来的一样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class OrderBroadcastActivity extends AppCompatActivity implements View.OnClickListener {
private View sendBroadcast;
public static final String KEY_VALUE = "KEY_VALUE";
public static final String MESSAGE_FROM_SENDER = "MESSAGE_FROM_SENDER";
public static final String ACTION_ORDER_BROADCAST = "example.broadcast.com.broadcastexample.ACTION_ORDER_BROADCAST";
public static final String PERMISSION_ORDER_BROADCAST = "example.broadcast.com.broadcastexample.PERMISSION_ORDER_BROADCAST";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_broadcast);
sendBroadcast = findViewById(R.id.send_broadcast);
}
@Override
protected void onStart() {
super.onStart();
sendBroadcast.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_broadcast) {
// 1. 创建一个 Intent 对象;
Intent intent = new Intent();
// 2. 设置 Action;
intent.setAction(ACTION_ORDER_BROADCAST);
// 3. 设置传值内容
intent.putExtra(KEY_VALUE, MESSAGE_FROM_SENDER);
// 4. 发送普通广播
sendOrderedBroadcast(intent, PERMISSION_ORDER_BROADCAST);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}

接下来是三个广播监听:
先看BroadcastReceiverOne

1
2
3
4
5
6
public class BroadcastReceiverOne extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(OrderBroadcastActivity.class.getCanonicalName(), "BroadcastReceiverOne receive message " + intent.getStringExtra(OrderBroadcastActivity.KEY_VALUE));
}
}

然后BroadcastReceiverTwo

1
2
3
4
5
6
public class BroadcastReceiverTwo extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(OrderBroadcastActivity.class.getCanonicalName(), "BroadcastReceiverTwo receive message " + intent.getStringExtra(OrderBroadcastActivity.KEY_VALUE));
}
}

然后BroadcastReceiverThree

1
2
3
4
5
6
public class BroadcastReceiverThree extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(OrderBroadcastActivity.class.getCanonicalName(), "BroadcastReceiverThree receive message " + intent.getStringExtra(OrderBroadcastActivity.KEY_VALUE));
}
}

然后需要在AndroidManifest.xml中进行注册:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<manifest ...>
<permission android:name="example.broadcast.com.broadcastexample.PERMISSION_ORDER_BROADCAST" />
<uses-permission android:name="example.broadcast.com.broadcastexample.PERMISSION_ORDER_BROADCAST" />
<application ...>
<activity android:name=".OrderBroadcastActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".broadcast.BroadcastReceiverOne">
<intent-filter android:priority="1000">
<action android:name="example.broadcast.com.broadcastexample.ACTION_ORDER_BROADCAST" />
</intent-filter>
</receiver>
<receiver android:name=".broadcast.BroadcastReceiverTwo">
<intent-filter android:priority="900">
<action android:name="example.broadcast.com.broadcastexample.ACTION_ORDER_BROADCAST" />
</intent-filter>
</receiver>
<receiver android:name=".broadcast.BroadcastReceiverThree">
<intent-filter android:priority="800">
<action android:name="example.broadcast.com.broadcastexample.ACTION_ORDER_BROADCAST" />
</intent-filter>
</receiver>
</application>
</manifest>

好了,长相还是一样的,点击按钮以后,发送ACTION为example.broadcast.com.broadcastexample.ACTION_ORDER_BROADCAST的广播,会看到
三条打印信息,分别是:

1
2
3
09-16 12:51:45.439 20457-20457/example.broadcast.com.broadcastexample D/example.broadcast.com.broadcastexample.OrderBroadcastActivity: BroadcastReceiverOne receive message MESSAGE_FROM_SENDER
09-16 12:51:45.444 20457-20457/example.broadcast.com.broadcastexample D/example.broadcast.com.broadcastexample.OrderBroadcastActivity: BroadcastReceiverTwo receive message MESSAGE_FROM_SENDER
09-16 12:51:45.452 20457-20457/example.broadcast.com.broadcastexample D/example.broadcast.com.broadcastexample.OrderBroadcastActivity: BroadcastReceiverThree receive message MESSAGE_FROM_SENDER

无论点击多少次,都是这个顺序打印,如果在BroadcastReceiverOne和BroadcastReceiverTwo中分别加入睡眠1s的逻辑,会慢慢打印三条信息。

这里有个非常好玩的地方,上面我们分别睡眠1秒,如果我们加大这个时间,分别睡眠10秒,代码我就不贴了,你会发现,直接ANR,好了原因我想大家也都知道,这是因为BroadcastReceiver的任务是在主线程里面执行的,所以,如果你想要做耗时操作的话,重新开一个线程去做。

有序广播可以选择是否终止,如果终止以后,那么后面的优先级较低的广播接受者就再也接收不到这条广播了。为了验证,我们在BroadcastReceiverTwo中先加入abortBroadcast(),

1
2
3
4
5
6
7
public class BroadcastReceiverTwo extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(OrderBroadcastActivity.class.getCanonicalName(), "BroadcastReceiverTwo receive message " + intent.getStringExtra(OrderBroadcastActivity.KEY_VALUE));
abortBroadcast();
}
}

这个时候我们的控制台得到的就只有两条信息了,

1
2
09-16 12:51:45.439 20457-20457/example.broadcast.com.broadcastexample D/example.broadcast.com.broadcastexample.OrderBroadcastActivity: BroadcastReceiverOne receive message MESSAGE_FROM_SENDER
09-16 12:51:45.444 20457-20457/example.broadcast.com.broadcastexample D/example.broadcast.com.broadcastexample.OrderBroadcastActivity: BroadcastReceiverTwo receive message MESSAGE_FROM_SENDER

如果我们在BroadcastReceiverOne中加入,就只剩下一条了,好了,以此类推,这个就不做实验了。

第三个知识点是,前面的广播可以往后续的广播传值,比如我们的BroadcastReceiverOne想要往后传递值,可以这样:
先看BroadcastReceiverOne

1
2
3
4
5
6
7
8
9
10
11
12
public class BroadcastReceiverOne extends BroadcastReceiver {
public static final String KEY_BROAD_CAST_ONE = "KEY_BROAD_CAST_ONE";
public static final String MESSAGE_FROM_BROAD_CAST_ONE = "MESSAGE_FROM_BROAD_CAST_ONE";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(OrderBroadcastActivity.class.getCanonicalName(), "BroadcastReceiverOne receive message " + intent.getStringExtra(OrderBroadcastActivity.KEY_VALUE));
Bundle bundle = new Bundle();
bundle.putString(KEY_BROAD_CAST_ONE, MESSAGE_FROM_BROAD_CAST_ONE);
setResultExtras(bundle);
}
}

然后BroadcastReceiverTwo

1
2
3
4
5
6
7
public class BroadcastReceiverTwo extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(OrderBroadcastActivity.class.getCanonicalName(), "BroadcastReceiverTwo receive message " + intent.getStringExtra(OrderBroadcastActivity.KEY_VALUE));
Log.d(OrderBroadcastActivity.class.getCanonicalName(),getResultExtras(true).getString(BroadcastReceiverOne.KEY_BROAD_CAST_ONE));
}
}

然后BroadcastReceiverThree

1
2
3
4
5
6
7
public class BroadcastReceiverThree extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(OrderBroadcastActivity.class.getCanonicalName(), "BroadcastReceiverThree receive message " + intent.getStringExtra(OrderBroadcastActivity.KEY_VALUE));
Log.d(OrderBroadcastActivity.class.getCanonicalName(), getResultExtras(true).getString(BroadcastReceiverOne.KEY_BROAD_CAST_ONE));
}
}

再次点击按钮,发现前面的值传递给了后面,OK,到此,有序广播就讲到这吧。

粘性广播 (Sticky Broadcast)

一般来说,当广播接收者的 onReceive() 方法的执行时间超过 10 秒,系统在资源不足时有可能将其结束掉而不让其执行。但是粘性广播没有这个限制,粘性广播的 Intent 会一直保持到广播结束,没有 10 秒的限制。

自定义一个 BroadcastReceiver,让其在接收到广播后循环 10 次,每次休眠 5 秒,并在休眠结束之后打印点东西:
StickyBroadcastActivity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class StickyBroadcastActivity extends AppCompatActivity implements View.OnClickListener {
private View sendBroadcast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendBroadcast = findViewById(R.id.send_broadcast);
}
@Override
protected void onStart() {
super.onStart();
sendBroadcast.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_broadcast) {
// 1. 创建一个 Intent 对象;
Intent intent = new Intent();
// 2. 设置 Action;
intent.setAction(BroadcastReceiverSticky.ACTION_STICKY_BROADCAST);
// 3. 发送粘性广播
sendStickyBroadcast(intent);
}
}
}

然后是我们定义的广播:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class BroadcastReceiverSticky extends BroadcastReceiver {
public static final String ACTION_STICKY_BROADCAST = "example.broadcast.com.broadcastexample.ACTION_STICKY_BROADCAST";
public static final String TAG = BroadcastReceiverSticky.class.getCanonicalName();
@Override
public void onReceive(Context context, Intent intent) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "收到了粘性广播" + i);
}
}
}).start();
}
}

然后在AndroidManifest.xml中声明,并设置过滤器:

1
2
3
4
5
<receiver android:name=".broadcast.BroadcastReceiverSticky">
<intent-filter>
<action android:name="example.broadcast.com.broadcastexample.ACTION_STICKY_BROADCAST" />
</intent-filter>
</receiver>

当我们点击了一次按钮之后,发送了一个粘性广播,当接收者接收到广播之后,就会执行相应的操作,仔细留意,时间已经超过 10 秒,而广播仍在继续,为了使结果更加富有准确性,可以开多几个程序,使系统开销增大,观察广播超过 10 秒后是否仍在继续。

广播的生命周期

广播接收者的生命周期非常短暂,在接收到广播的时候创建,onReceive() 方法结束后销毁。
由于 BroadcastReceiver 的设计之初是从全局考虑的,可以方便应用程序和系统、应用程序之间、应用程序内的通信,所以对单个应用程序而难免存在安全方面的问题
,所以,为了避免安全问题,可以从以下几个方面入手:

发送广播时:
发送带权限的广播,在发送广播时指定权限,这样接收者就必须声明对应的权限才能接收到该广播;
指定接收广播的应用包名,Intent.setPackage(“com.package.name”);
注册广播时:
注册广播时指定权限;
注册广播时使用 androd:exported=”false”,声明不接收外部应用的广播;
使用本地广播 LocalBroadcastManager,其用于应用内部之间传播,不会泄露给外部应用:

1
2
3
4
5
6
7
8
9
// 1. 获取本地广播管理器对象
LocalBroadcastManager.getInstance(Context context);
// 2. 注册广播
registReceiver(BroadcastReceiver receiver, IntentFilter flter);
// 3. 发送广播
sendBroadcast(Intent); // 发送异步广播
// sendBroadcastSync(Intent intent); // 发送同步广播
// 4. 注销注册
unregisterReceiver(BroadcastReceiver receiver)

总结

了解广播的特性和使用方法,在我们的程序开发中可能会起到事半功倍的作用,需要注意的地方也挺多,比如别到广播中去睡眠等等~总的来说,广播是个很好的安卓机制,开发过程中多多使用。

不想敲代码就到我的git来拉一下吧~https://github.com/gordon-rawe/understandBroadcast