一、知识介绍
1、【广播分类】
①有序广播:接收者A收到广播传递给B,B传给C,有序传递。任何一个环节都可以终止广播,也可以修改广播中携带的数据。
发送的方式:sendOrderedBroadcast(intent,receiverPermission);
【提示】①第二个参数是设置发送的权限,这里可以设为null
②接收有序广播是需要在intent-flter中设置priority,值越大则先执行,相同则按照注册顺序
②无序广播:一个广播发送者,向所有接收者同时发送广播,也就是ABC接收者都同时响应。
发送方式:sendBroadcast(intent)
2、【广播接收者】按是否常驻分类
①常驻型广播接收者:在androidManifest.xml中注册,只要应用程序没有被卸载就持续存在。
②非常驻型广播接收者:在java代码中注册,一般随Activity或者Service组件产生而产生,随他们销毁而销毁。生命周期比较短。使用的方法是registerReceiver(参数1:广播接收者实例,参数2:频道(意图过滤器));unregisterReceiver(广播接收者实例)
二、项目一【发送广播】
【步骤】
①定义一个广播接收者,自定义添加intent-fliter中的action name
②添加按钮,点击事件
③定义intent,设置action,发送广播
【项目结构】
【MyReceiver】
1 importandroid.content.BroadcastReceiver;2 importandroid.content.Context;3 importandroid.content.Intent;4 importandroid.widget.Toast;5
6 public class MyReceiver extendsBroadcastReceiver {7
8 @Override9 public voidonReceive(Context context, Intent intent) {10 //TODO: This method is called when the BroadcastReceiver is receiving
11 Toast.makeText(context, "收到广播", Toast.LENGTH_SHORT).show();12 }13 }
【AndroidManifest.xml】
1
3 android:enabled="true"
4 android:exported="true">
5
6
7
8
【activity_main.xml】
1
3 android:text="发送广播"
4 android:layout_width="match_parent"
5 android:layout_height="wrap_content" />
【MainActivity】
1 importandroid.content.Intent;2 importandroid.support.v7.app.AppCompatActivity;3 importandroid.os.Bundle;4 importandroid.view.View;5 importandroid.widget.Button;6
7 public class MainActivity extendsAppCompatActivity {8
9 Button btn;10 @Override11 protected voidonCreate(Bundle savedInstanceState) {12 super.onCreate(savedInstanceState);13 setContentView(R.layout.activity_main);14
15 btn =findViewById(R.id.btn);16 btn.setOnClickListener(newView.OnClickListener() {17 @Override18 public voidonClick(View view) {19 Intent intent = new Intent("com.example.MyApplication2.myreceiver");20 sendBroadcast(intent);21 }22 });23
24 }25 }
【提示】发送广播intent设置的action要和广播接受者设置的action相同,这样广播接收者才能收到发送的广播
【效果】点击
二、项目二【发送有序广播】
【步骤】
①定义三个广播接收者,观察顺序
②添加按钮点击
③设置intent,发送有序广播
【项目结构】
【定义三个广播接收者并注册】
1
3 android:enabled="true"
4 android:exported="true">
5
6
7
8
9
11 android:enabled="true"
12 android:exported="true">
13
14
15
16
17
19 android:enabled="true"
20 android:exported="true">
21
22
23
24
【提示】设置priority为不同的值,action name为相同的,接收同一个广播
【MainActivity】
1 btn2 =findViewById(R.id.btn2);2 btn2.setOnClickListener(newView.OnClickListener() {3 @Override4 public voidonClick(View view) {5 Intent intent = new Intent("com.example.MyApplication2.myreceiver");6 sendOrderedBroadcast(intent,null);7 }8 });
【效果】
点击按钮执行顺序