一.自定义标准广播
1.新建MyBroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "收到一条广播", Toast.LENGTH_LONG).show();
}
}
2.发送广播
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void myClick(View view){
if( view.getId() == R.id.btn ){
Intent intent = new Intent("com.example.guo.broadcast3.SEND_BROADCAST3");
sendBroadcast(intent);
}
}
}
3.AndroidManifest.xml配置
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.guo.broadcast3.SEND_BROADCAST3" />
</intent-filter>
</receiver>
二.自定义有序广播
1.广播可以被本应用接收到,也可以被别的应用接收到,我们新建一个Broadcast4应用
2.新建AnotherBroadcastReceiver
public class AnotherBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "收到一条广播,来自broadcast3", Toast.LENGTH_LONG).show();
}
}
3.配置AndroidManifest.xml,让它接收上一个应用broadcast3的广播
<receiver android:name=".AnotherBroadcastReceiver">
<intent-filter>
<action android:name="com.example.guo.broadcast3.SEND_BROADCAST3" />
</intent-filter>
</receiver>
4.运行broadcast3,点击发送广播后,broadcast3和broadcast4都会收到广播消息
5.更改broadcast3的发送为有序发送
sendOrderedBroadcast(intent, null);
6.修改broadcast3中的AndroidManifest.xml,提高接收优先级
<receiver android:name=".MyBroadcastReceiver">
<intent-filter android:priority="100">
<action android:name="com.example.guo.broadcast3.SEND_BROADCAST3" />
</intent-filter>
</receiver>
增加一个优先级字段android:priority="100"
7.运行broadcast3,点击发送广播后,broadcast3和broadcast4都会收到广播消息,但是广播是先发送给优先级高的broadcast3,后发送给broadcast4
8.我们在broadcast3收到广播消息后,阻断继续发送.
Toast.makeText(context, "收到一条广播", Toast.LENGTH_LONG).show();
abortBroadcast();
9.再次运行,发现只有broadcast3收到消息,broadcast4没有收到消息