BrocastReceiver(一)

来源:互联网 发布:mac移动文件到文件夹 编辑:程序博客网 时间:2024/06/01 09:17

广播(BrocastReceiver)是Android四大组件之一


两者注册方式
1.在java代码中注册   动态广播
注册广播
myBrocastReceiver1=new MyBrocastReceiver();
IntentFilter filter=new IntentFilter();
filter.addAction(myAction1);//只有有相同的action的接受者才能接收此广播
registerReceiver(myBrocastReceiver1, filter);


注销广播
if(null!=myBrocastReceiver1){
   unregisterReceiver(myBrocastReceiver1);
}


 发送广播
Intent intent=new Intent();  
intent.setAction(myAction1);//设置广播的action 只有和这个action一样的接受者才能接受者才能接收广播
intent.putExtra("date1", "张三");
intent.putExtra("date2", "李四");
intent.putExtra("date3", "王五");
sendBroadcast(intent);//发送广播




2.在清单文件中注册  静态广播
注册广播
<receiver
   android:name="com.finddreams.runningman.MyBrocastReceiver"
   android:exported="false" >
   <intent-filter>
           <action android:name="com.finddreams.runningman.brocastreceiver3" />
   </intent-filter>
</receiver>


 发送广播
Intent intent=new Intent();  
intent.setAction(myAction3);//设置广播的action 只有和这个action一样的接受者才能接受者才能接收广播
intent.putExtra("date1", "男");
intent.putExtra("date2", "女");
intent.putExtra("date3", "男");
sendBroadcast(intent);//发送广播


总结
动态注册广播不是常驻型广播,也就是说广播跟随activity的生命周期。注意: 在activity结束前,移除广播接收器。
静态注册是常驻型,也就是说当应用程序关闭后,如果有信息广播来,程序也会被系统调用自动运行。


当广播为有序广播时:
1 优先级高的先接收
2 同优先级的广播接收器,动态优先于静态
3 同优先级的同类广播接收器,静态:先扫描的优先于后扫描的,动态:先注册的优先于后注册的。


当广播为普通广播时:
1 无视优先级,动态广播接收器优先于静态广播接收器
2 同优先级的同类广播接收器,静态:先扫描的优先于后扫描的,动态:先注册的优先于后注册的。
3.4静态广播使用示例:这里以开机启动为例(电池电量过低,设备内存不足...)


系统广播(以开机启动app为例)


 清单中注册广播
2. <receiver android:name=".AutoStartReceiver">  
3.     <intent-filter>  
4.         <action android:name="android.intent.action.BOOT_COMPLETED"/>  
5.         <category android:name="android.intent.category.HOME"/>  
6.     </intent-filter>  
7. </receiver> 


权限设置 
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 


onReceive方法中
Intent i = new Intent(context, MainActivity.class);  
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
context.startActivity(i); 
0 0