静态注册广播
①静态注册广播接收者
创建一个MyReceiver类作为广播接收者
1 2 3
| public class MyReceiver{ }
|
该类继承自BroadcastReceiver,并重写了onReceive方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("message"); Toast.makeText(context,msg,Toast.LENGTH_SHORT).show(); } }
|
在清单文件的application中注册广播接收类
1 2
| <receiver android:name=".MyReceiver"/>
|
清单文件中注册后,需要给它一个标记,通过这个标记找到广播接收类
1 2 3 4 5 6 7
| <receiver android:name=".MyReceiver"> <intent-filter>
<action android:name="com.test.myReceiver"/> </intent-filter> </receiver>
|
②发送广播给接收者
在事件中
1 2 3 4 5 6 7 8 9 10
| Intent intent = new Intent();
intent.setAction("com.test.myReceiver");
intent.putExtra("message","MainActivity发送的消息");
intent.setComponent(new ComponentName(getPackageName(),getPackageName().toString()+".MyReceiver"));
sendBroadcast(intent);
|
在Android8.0以上,静态广播必须设置和
1 2 3 4
| ComponentName componentName = new ComponentName(getPackageName(),getPackageName()+".MyReceiver");
intent.setComponent(componentName);
|
动态注册广播
①动态注册广播接收者
创建一个MyReceiver类作为广播接收者
1 2 3
| public class MyReceiver{ }
|
该类继承自BroadcastReceiver,并重写了onReceive方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("message"); Toast.makeText(context,msg,Toast.LENGTH_SHORT).show(); } }
|
动态注册广播接收类
1 2 3 4 5 6 7 8
| MyReceiver myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.test.myReceiver");
registerReceiver(myReceiver,intentFilter);
|
②发送广播给接收者
在事件中
1 2 3 4 5 6 7 8
| Intent intent = new Intent();
intent.putExtra("message","MainActivity发送的消息");
intent.setAction("com.test.myReceiver");
sendBroadcast(intent);
|
动态注册广播一定不要设置setComponent()
发送广播的方式
①sendBroadcast
所有满足条件的广播接收者都会执行其onReceive()方法来处理响应,当有多个满足条件的广播接收者时,不能保证它们onReceive()的执行顺序
②sendStickyBroadcast
intent在发送后一直存在,并且在以后调用registerReceiver注册相匹配的Receive时会把这个intent直接返回给新注册的Receive
通俗讲:先动态注册再发送广播,或者先发送广播再动态注册,intent都可以被接收器接收到并执行其onReceive方法。
不过需要在manifest.xml文件中配置此类型广播权限
1
| <uses-permissionandroid:name="android.permission.BROADCAST_STICKY"/>
|
③sendOrderBroadcast
通过sendOrderBroadcast发送广播,当有多个满足条件的广播接收者,会根据广播接收者注册时intentFilter设置的优先级顺序来执行onReceive()方法,对于相同优先级的广播接收者则不能保证onReceive()的执行顺序