一、标准广播和有序广播也很容易理解的。
标准广播:
(1)通过sendBroadcast()方法发送
(2)通过异步方式发送,广播接收者的执行顺序是不明确的
有序广播:
(1)通过sendOrderBroadcast()发送
(2)广播接收者需要按照优先级依次执行
(3)可以使用setResultXXX()、getResultXXX()、abortBroadcast()方法
二、通过简单例子来实现一下标准广播和有序广播
1、很简单的例子,先看一下主布局。
2、主活动需要实现发送标准广播和有序广播,下面是主活动核心代码。
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("com.thanlon.broadcastReceiverType");
switch (view.getId()) {
case R.id.order_send_btn://发送有序广播,有序广播通过优先级去
sendOrderedBroadcast(intent, null);
Log.d("Thanlon","发送了有序广播");
break;
case R.id.disorder_send_btn://发送标准广播
sendBroadcast(intent, null);
Log.d("Thanlon","发送了标准广播");
break;
}
}
}
3、接收广播的类。
这里写了三个继承了BroadcastReceiver的类来实现接收广播:
MyBroadcastReveiver1.java:
public class MyBroadcastReveiver1 extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Thanlon","MyBroadcastReveiver1接收到广播");
}
}
MyBroadcastReveiver2.java:
public class MyBroadcastReveiver2 extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Thanlon","MyBroadcastReveiver1接收到广播");
}
}
MyBroadcastReveiver3.java:
public class MyBroadcastReveiver3 extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Thanlon","MyBroadcastReveiver1接收到广播");
}
}
4、注册BroadcastReceiver
AndroidManifest.xml:(在<application>标签里,<activity>结束标签的下面添加如下代码)
<receiver android:name=".MyBroadcastReveiver1">
<!--优先级通过取值来判断优先级先后,优先级取值为-1000~1000,值越大优先级越高,越先接收广播;如果优先级一样,则哪个广播先注册就先执行-->
<intent-filter android:priority="1">
<action android:name="com.thanlon.broadcastReceiverType" />
</intent-filter>
</receiver>
<receiver android:name=".MyBroadcastReveiver2">
<intent-filter android:priority="2">
<action android:name="com.thanlon.broadcastReceiverType" />
</intent-filter>
</receiver>
<receiver android:name=".MyBroadcastReveiver3">
<intent-filter android:priority="3">
<action android:name="com.thanlon.broadcastReceiverType" />
</intent-filter>
</receiver>
当发送有序广播的时,要根据优先级来判断哪个广播先执行。为了很好的证明,在配置文件中设置了不同的优先级。如果优先级相同,如何判断哪个先执行?先注册的,先执行。
5、测试
很明显有序广播是由优先级的高低来决定的。由于接收广播的类较少,标准广播不易被体现出来,只需知道就收广播的顺序是不同的就行了,在这里不进行演示。