美文网首页Android
广播接收者(BroadcastReceiver)

广播接收者(BroadcastReceiver)

作者: ProZoom | 来源:发表于2017-09-22 13:06 被阅读55次

    广播接收者(BroadcastReceiver)

    1.定义广播接受者

    静态注册广播

    • 定义类继承BroadcastReceiver,重写onReceive方法

      public class BroadCastReceiverDemo extends BroadcastReceiver {
      
        @Override
        public void onReceive(Context context, Intent intent) {
      
            Toast.makeText(context,"广播接受者--Boot Complete.",Toast.LENGTH_LONG).show();
        }
      
      }
      
    • 清单文件中声明<receiver>,需要在其中配置<intent-filter>指定接收广播的动作

      <!-- 开机广播接受者 -->
      <receiver android:name=".BroadCastReceiverDemo">
           <intent-filter>
                <!-- 注册开机广播地址-->
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
       </receiver>
      
    • 当接收到匹配广播之后就会执行onReceive方法

       @Override
        public void onReceive(Context context, Intent intent) {
      
            Toast.makeText(context,"广播接受者----Boot Complete.",Toast.LENGTH_LONG).show();
        }
      
    • BroadcastReceiver的优先级

       <!-- 开机广播接受者 -->
      <receiver android:name=".BroadCastReceiverDemo">
           <intent-filter android:priority="2147483647">
                <!-- 注册开机广播地址-->
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
       </receiver>
      

      2147483647是最高优先级,默认是0.

    动态注册广播

    • BroadcastReceiver除了在清单文件中声明,也可以在代码中声明,使用registerReceiver方法注册Receiver

      public class MainActivity extends Activity {
      
         private CodeReceiver receiver;
         private IntentFilter filter;
      
         @Override
         protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              filter = new IntentFilter("android.intent.action.SCREEN_ON");
              filter.setPriority(100);             //优先级
              receiver = new CodeReceiver();
             
              registerReceiver(receiver, filter);  // Activity创建时注册接收者
         }
        
         @Override
         protected void onDestroy() {
              super.onDestroy();
              unregisterReceiver(receiver);       // Activity退出时注销接收者
         }
      
      }
      

    2.发送广播

    无序广播

    • 使用sendBroadcast方法发送
    • 被所有广播接收者接收,无序,不可中断
    • 广播时可设置接收者权限,仅当接收者含有权限才能接收
    • 接收者的<receiver>也可设置发送方权限,只接收含有权限应用的广播

    无序广播发送方法

    void sendBroadcast (Intent intent, String receiverPermission)
    

    参数:

    intent The Intent to broadcast; 传给接收者的意图 all receivers matching this Intent will receive the broadcast.所有匹配的广播接受者都回收到这一意图

    receiverPermission (optional)可选的 String naming a permission that a receiver must hold in order to receive your broadcast.一个接收者必须拥有的权限 If null, no permission is required. 如果为null,则没有要求

    示例:

    sendBroadcast(intent, null);
    

    有序广播

    • 使用sendOrderedBroadcast方法发送
    • 接收者可以在<intent-filter>中定义android:priority定义优先级,数字越大优先级越高
    • 被各个广播接收者逐个接收,中途可以中断或者添加数据
    abortBroadcast()  
    getResultExtras(true).putString("data", "新增数据");
    
    <receiver android:name="com.top.myreceiver.MyReceiver1" >
         <intent-filter android:priority="1000">
             <action android:name="com.top.mybroadcast.xxx" />
         </intent-filter>
    </receiver>
    
    <receiver android:name="com.top.myreceiver.MyReceiver2" >
        <intent-filter android:priority="500">
          <action android:name="com.top.mybroadcast.xxx"/>
        </intent-filter>
    </receiver>
            
    <receiver android:name="com.top.myreceiver.MyReceiver3" >
        <intent-filter android:priority="100">
             <action android:name="com.top.mybroadcast.xxx" />
        </intent-filter>
    </receiver>
    
    
    • 有序广播发送方法
    void sendOrderedBroadcast (Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)
    

    参数
    intent* The Intent to broadcast; 传给接收者的意图 all receivers matching this Intent will receive the broadcast.所有匹配的广播接受者都回收到这一意图

    receiverPermission (optional)可选的 String naming a permission that a receiver must hold in order to receive your broadcast.一个接收者必须拥有的权限 If null, no permission is required. 如果为null,则没有要求

    resultReceiver Your own BroadcastReceiver to treat as the final receiver of the broadcast. 指定一的广播的最终接受者(必须执行的)
    scheduler A custom Handler with which to schedule the resultReceiver callback;指定你的接收者回掉的handler; if null it will be scheduled in the Context's main thread. 如果为空,则默认为主线程
    initialCode An initial value for the result code.初始的结果码 Often Activity.RESULT_OK. 通常设置

    initialData An initial value for the result data.初始的结果数据 Often null. 通常为null

    initialExtras An initial value for the result extras.初始化附加信息bundle; Often null通常为null

    示例

    Intent intent = new Intent("com.top.broadcast.TEST");         // 创建意图对象, 设置广播的动作
    intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); // 广播是否启动那些没有启动过的应用
    intent.putExtra("data", "最初的数据!!!");                                  // 这里的数据不会被修改
    Bundle bundle = new Bundle();
    bundle.putString("name", "张三");
    sendOrderedBroadcast(intent, "com.top.permission.BROADCAST", new ResultReciever(), null, 1, "MainActivity", bundle);
    

    短信黑名单

    • Android系统在收到短信的时候会发送一条有序广播,我们如果定义一个接收者接收这个广播,就可以得到短信内容,也可以拦截短信
    • 定义广播接收者接收广播android.provider.Telephony.SMS_RECEIVED
    • 在onReceive方法内部调用Intent的getExtras()再调用get()获取其中pdus字段,得到一个Object[],其中每一个元素都是一个byte[]
    • 通过SmsMessage类的createFromPdu方法创建SmsMessage对象
    • 从SmsMessage对象中即可获取发送者号码、短信内容、发送时间等信息
    • 需要接收短信权限:<uses-permission android:name="android.permission.RECEIVE_SMS"/>
    • Android系统中收到短信的通知是一个有序通知,我们如需拦截垃圾短信,可以配置较高的priority,收到信息进行判断是否abortBroadcast()

    自动IP拨号

    • 定义广播接收者接收 android.intent.action.NEW_OUTGOING_CALL
    • 需要权限 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
    • 在onReceive方法中使用getResultData() 和 setResultData() 方法获取和设置电话号码

    广播接收者生命周期 Broadcast receiver lifecycle

    • 广播接收者的生命周期是非常短暂的,在接收到广播的时候创建,onReceive()方法结束之后销毁。当广播消息抵达接收器时,Android调用它的onReceive()方法并将包含消息的Intent对象传递给它。广播接收器仅在它执行这个方法时处于活跃状态。当onReceive()返回后,它即为失活状态。
      拥有一个活跃状态的广播接收器的进程被保护起来而不会被杀死。但仅拥有失活状态组件的进程则会在其它进程需要它所占有的内存的时候随时被杀掉。
      //广播接收器只有一个回调方法:void onReceive(Context curContext, Intent broadcastMsg)
    • 广播接收者是在主线程中执线的,广播接收者中不要做一些耗时的工作,否则会弹出Application No Response错误对话框
    • 最好也不要在广播接收者中创建子线程做耗时的工作,因为广播接收者被销毁后进程就成为了空进程,很容易被系统杀掉
    • 耗时的较长的工作最好放在服务中完成

    在android系统里面有很多内置的广播事件

    相关文章

      网友评论

      • 书山有路学海无涯:创建两个接受者,都不能拦截短信。请问是怎么回事啊
        书山有路学海无涯:@ProZoom https://github.com/yapingGitHub/AlarmBall/blob/master/app/src/main/java/com/shdcec/alarmball/phone/SMSMonitorReceiver.java🍻
        ProZoom:@书山有路学海无涯 我看看源码

      本文标题:广播接收者(BroadcastReceiver)

      本文链接:https://www.haomeiwen.com/subject/utcfextx.html