现在的位置: 首页 > 综合 > 正文

Android学习笔记(二)——–浅谈Broadcast 广播

2018年06月05日 ⁄ 综合 ⁄ 共 1561字 ⁄ 字号 评论关闭

浅谈BroadCast        

上节回顾,上节博客浅谈了Intent是什么,有何作用,如何用。上节主要围绕Intent发送请求给activity做了说明,本节主要说明BroadCast如何使用。

  一、广播               

    前面已经看到,Intent可以启动新的应用程序组件,实际上他们也可以使用sendBroadcast方法在组件中匿名的广播消息。
在Android中,Broadcast是一种广泛运用的在应用程序之间传输信息的机制。而BroadcastReceiver是对发送出来的 Broadcast进行过滤接受并响应的一类组件。下面将详细的阐述如何发送Broadcast和使用BroadcastReceiver过滤接收的过程:

 二、使用Intent发送广播   

1、发送普通广播:sendBroadcast();                           

   动作(action):习惯上,动作字符串使用与java包名相同的构造方式

public staitc final String NEW_LEFTFORM_DETECTED="com.paad.action.NEW_LIFEFORM";

   数据:

Intent intent=new Intent(LifeformDetectedReceiver.NEW_LEFTFORM_DETECTEDF)
intent.putExtra(LifeformDetectedReceiver.EXTRA_LITEFORM_NAME,detectedLifeform);

   发送广播:

sendBroadCast(intent);

   2、发送有序广播:

sendOrderedBroadcast(intent,requiredPermission);

3、广播Sticky Intent
           sticky Intent是BroadCast Intent 的有用变体,可以保存他们最后一次广播的值。并且当有一个新的接收器被注册为接受该广播时,它们会把这些值作为Intent返回。

sendStickyBroadCast(Intent);

三、使用Broadcast  Receiver来监听广播

  通常Broadcast Receiver成为广播接收器,可以用来监听BroardCast Intent ,要是BroadCast Receiver能够接收广播Intent必须进行注册,一下为使用方法。
     首先,实现broadcast Recevier类,重写onReceive事件

 public class MyBroadcastRecevier extends BroadCastReceiver{
			public void onReceiver (Context context,Intent intent){
			}
		}

      注册使用方法:
       1、静态注册
        是在manifest文件中进行注册,此处注册时,应用程序不一定需要在运行状态才能接收。

<receiver android:name=".LifeformDetectedRecevier">
 <intent-filter>
    <action  android:name="com.paad.alien.action.NEW_LITEFORM"/>
 <intent-filter/>
<receiver/>

    2、动态注册                  
       在代码中注册广播,registerReceiver(receiver,filter);
       注销广播,unregisterReceiver(receiver);

无论,如何注册广播,都需要使用Intent Filter来指定它要监听那些Intent和数据。

四、局部广播管理器(Local BroadCast Manager)

    局部广播,的作用域要小一些,因此以普通广播更高效。

抱歉!评论已关闭.