zoukankan      html  css  js  c++  java
  • BroadcastReceiver

    BroadcastReceiver

    BroadcastReceiver是用来过滤、接收并响应广播的一类组件。
    通过广播接收者可以监听系统中的广播消息,在不同组件之间进行通信。

    广播接收者的创建与注册

    1. 创建一个类继承BroadcastReceiver
      public class 类名 extends BroadcastReceiver
    2. 注册广播
    • 注册常驻型广播

       	<!--action的name中写要监听的广播,自定义广播中这里要自己定义-->
       	<receiver android:name="com.example.test_broadcastreceiver.OutCallReceiver">
       		<intent-filter android:priority="99">
       			<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
       		</intent-filter>
       	</receiver>
      
    • 注册非常驻型广播

       	//Outcall是继承BroadcastReceiver的类
       	OutCallReceiver receiver = new OutCallReceiver();
       	String action = "android.intent.action.NEW_OUTGOING_CALL";
       	IntentFilter filter = new IntentFilter(action);
       	registerReceiver(receiver, filter);
      
    1. 重写继承BroadcastReceiver类中的onReceive方法

       public void onReceive(Context context, Intent intent) {
       }
      

    示例代码BroadcastReceiver

    自定义广播

    当系统级别的广播事件不能满足实际需求时,可以自定义广播。
    自定义广播需要由对应的广播接收者去接收,否则这个广播是无意义的。

    自定义广播与上面“广播接收者的创建与注册”的写法差不多,以下是主要代码。

    //action是自定义的广播事件类型
    Intent intent = new Intent();
    String action = "www.itcast.cn";
    intent.setAction(action);
    sendBroadcast(intent);
    

    同时要在清单文件中配置事件类型

    //这里的action name必须要与上面的action相同
    <receiver android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="www.itcast.cn"/>
        </intent-filter>
    </receiver>
    

    示例代码Custom_Broadcast

    广播的类型

    根据广播的执行顺序不同,可以分为有序广播和无序广播。

    • 无序广播
      无序广播是一种完全异步执行的广播,在广播发出去之后,
      所有监听了这个广播事件的广播接收器几乎都会在同一时刻接收到这条广播,
      他们之间没有任何先后顺序可言。

      这种广播效率较高,但是不能被拦截。

    • 有序广播
      有序广播是一中同步执行的广播,在广播发出之后,同一时刻只会有一个广播接收器能够接收到这条消息,
      当这个广播接收器中的逻辑执行完毕后,广播才会继续传递。

      这个时候的广播接收器是有先后顺序的,可以被拦截。

    有序广播发送一条消息后,高优先级的广播接收器先接收到广播,低优先级的广播接收器后收到广播。
    如果高优先级的广播接收器将广播终止,后面的广播接收器将无法收到消息。

    用abortBroadcast()方法拦截广播。
    优先级在清单文件中的intent-filter结点中定义 android:priority=""参数

    拦截有序广播示例代码


    7月18日更新

    本地广播

    使用本地广播发出的广播只能够在应用程序的内部进行传递,并且广播接收器也只能接收来自本应用程序发出的广播。

  • 相关阅读:
    UVALive 5983 MAGRID DP
    2015暑假训练(UVALive 5983
    poj 1426 Find The Multiple (BFS)
    poj 3126 Prime Path (BFS)
    poj 2251 Dungeon Master 3维bfs(水水)
    poj 3278 catch that cow BFS(基础水)
    poj3083 Children of the Candy Corn BFS&&DFS
    BZOJ1878: [SDOI2009]HH的项链 (离线查询+树状数组)
    洛谷P3178 [HAOI2015]树上操作(dfs序+线段树)
    洛谷P3065 [USACO12DEC]第一!First!(Trie树+拓扑排序)
  • 原文地址:https://www.cnblogs.com/clevergirl/p/5677180.html
Copyright © 2011-2022 走看看