安卓四大组件之——BroadcastReceiver广播的详细解析

本文深入解析了安卓四大组件之一的BroadcastReceiver,介绍了静态与动态注册、有序与无序广播的区别和使用场景,并提供了示例代码。在实际应用中,讲解了如何在不同APP间发送和接收广播,同时总结了广播使用的关键点,包括生命周期和优先级规则。
摘要由CSDN通过智能技术生成

BroadcastReceiver 身为安卓的四大组件之一,其使用率非常普遍,所以我们要熟练掌握其使用方法。
1,广播的注册方式有两种:静态注册和动态注册
1),静态注册:需要在Androidmanifest 中进行声明,主要用于全局APP中监听,只有完全退出APP才能让其停止工作。
2),动态注册:在代码中注册,不需要在Androidmanifest进行声明,其生命周期随着活动的开始而开始,结束而结束,主要用于当前活动的监听。

2,广播的种类:有序广播和无序广播
1),有序广播:广播按照一定的顺序被接收,优先级高的比优先级低的先接收到,并且优先级高的可以阻断和添加数据给优先级低的广播。
2),无序广播:无论是否有广播接收器,都会发送广播,接收前后顺序不受优先级影响,也不能被阻断,接收器也不能对其修改。


效果图如下:
这里写图片描述
下面直接上代码:
主界面代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.btzh.mybroatcasttest.MainActivity">
   <Button
       android:text="无序广播"
       android:id="@+id/send_btn"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />
    <Button
        android:text="当前Activity广播"
        android:id="@+id/send_btn_1"
        android:layout_below="@id/send_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:text="有序广播"
        android:id="@+id/send_btn_2"
        android:layout_below="@id/send_btn_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:text=""
        android:id="@+id/text_view"
        android:layout_below="@id/send_btn_2"
        android:layout_width="match_parent"
        android:layout_height
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值