Broadcast 使用详解

640?wx_fmt=gif

640?wx_fmt=other

极力推荐文章:欢迎收藏Android 干货分享 

640?wx_fmt=other

本篇文章主要介绍 Android 开发中的部分知识点,通过阅读本篇文章,您将收获以下内容:

  1. 广播的生命周期

  2. 四大组件之一,必须在Androidmainfest.xml中注册

  3. 广播的注册(静态广播、动态广播)

  4. 广播的发送(正常、有序、持续)

  5. 广播接收(系统广播、自定义广播)

Broadcast是 Android 四大组件之一,是一种广泛运用在应用程序之间异步传输信息的机制。Broadcast 本质上是一个Intent 对象,差别在于Broadcast可以被多个 BroadcastReceiver处理。BroadcastReceiver 是一个全局监听器,通过它的 onReceive() 可以过滤用户想要的广播,进而进行其它操作。

1. BroadcastReceiver简介

BroadcastReceiver继承关系

BroadcastReceiver 默认是在主线程中执行,如果onReceiver()方法处理事件超过10s,则应用将会发生ANR(Application Not Responding),此时,如果建立工作线程并不能解决此问题,因此建议:如处理耗时操作,请用 Service代替。

BroadcastReceiver继承关系 如下:

java.lang.Object
   ↳    android.content.BroadcastReceiver

BroadcastReceiver的主要声明周期方法onReceiver(),此方法执行完之后,BroadcastReceiver实例将被销毁。

2.四大组件之一,必须在Androidmainfest.xml中注册

        <receiver
            android:name="ReceiverMethod"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="String....." />
            </intent-filter>
        </receiver>

注意:

3.广播的注册(静态注册、动态注册)

广播的注册分两种,一种在ndroidMfest.xml中静态注册,另一种是在Java代码中动态注册。

1.静态注册

一些系统发送的广播需要在Androidmainfest.xml中静态注册,例如 开机广播,apk状态改变广播,电量状态改变广播等。这些静态注册的广播,通常在Androidmainfest.xml中拦截特定的字符串。

静态注册广播的方法如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.programandroid"
    android:versionCode="1"
    android:versionName="1.0" >
         ... ...
        <receiver
            android:name="com.programandroid.BroadcastReceiver.NotificationReceived"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="Notification_cancel" />
                <action android:name="Notification_music_pre" />
                <action android:name="Notification_music_play" />
                <action android:name="Notification_music_next" />
            </intent-filter>
        </receiver>
        ... ...

1.静态注册开机广播方法

开机广播比较特殊,需要在Androidmainfest.xml中添加权限。否则,无法获取开机广播。

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

//静态注册广播的方法
        <receiver
            android:name=".component.BroadcastReceiver.BootReceiverMethod"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

2.动态注册广播

在Java中动态注册广播,通常格式如下:

  //动态注册广播
  registerReceiver(BroadcastReceiver, IntentFilter);

动态注册 监听灭屏、点亮屏幕的广播

在广播中动态注册广播请注意一定要使用context.getApplicationContext(),防止context为空 ,引起空指针异常。

public class ScreenOnOffReceiver {

    public static void ReceiverScreenOnOff(Context context) {
        IntentFilter screenOffFilter = new IntentFilter();
        screenOffFilter.addAction(Intent.ACTION_SCREEN_OFF);
        screenOffFilter.addAction(Intent.ACTION_SCREEN_ON);
        BroadcastReceiver mScreenOnOffReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                String action = intent.getAction();
                if (action.equals(Intent.ACTION_SCREEN_OFF)) {

                    Toast.makeText(context, "接收屏幕熄灭广播", Toast.LENGTH_SHORT).show();

                }
                if (action.equals(Intent.ACTION_SCREEN_ON)) {

                    Toast.makeText(context, "接收屏幕点亮广播", Toast.LENGTH_SHORT).show();
                }


            }

        };
        /**
         * context.getApplicationContext()
         * 在广播中注册广播时候需要注意,防止context 为空 ,引起空指针异常
         * **/
// 2.动态注册广播的方法
        context.registerReceiver(mScreenOnOffReceiver, screenOffFilter);

    }
}

4.广播的发送(无序、有序、持续)

1.发送无序广播的方法

发送无序广播在Android 中很常见,是一种一对多的关系,主要通过 sendBroadcast(intent);发送广播。

发送自定义广播案例

广播说白了就是一个带Action等字符串标记的Intent。发送自定义广播举例如下:

        Intent customIntent=new Intent();
        customIntent.setAction("SendCustomBroadcast");
        sendBroadcast(customIntent);

接收自定义广播的方法

当用户对某些广播感兴趣的话,此时可以获取此广播,然后在onReceive方法中处理接收广播的一下操作。


public class CustomBroadcast extends BroadcastReceiver {
    public CustomBroadcast() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("SendCustomBroadcast")){
            Toast.makeText(context,"自定义广播接收成功:Action:SendCustomBroadcast",Toast.LENGTH_SHORT).show();
        }
    }
}

注意自定义广播是在Androidmanfest.xml中静态注册的。

2.发送有序广播

广播在Android是有优先级的,优先级高的广播可以终止或修改广播内容。发送有序广播的方法如下sendOrderedBroadcast(intent,"str_receiver_permission");

例如:发送自定义有序广播
        Intent customOrderIntent=new Intent();
        customOrderIntent.setAction("SendCustomOrderBroadcast");
        customOrderIntent.putExtra("str_order_broadcast","老板说:公司每人发 10 个 月饼");
        sendOrderedBroadcast(customOrderIntent,"android.permission.ORDERBROADCAST");

广播属于四大组件,一定要在AndroidMainfest.xml中注册。

有序广播静态注册

接收有序广播的静态注册方法如下:

       <receiver
            android:name=".component.BroadcastReceiver.CustomHightBrodcast"
            android:enabled="true"
            android:exported="true"
           >
            <intent-filter android:priority="1000">
                <action android:name="SendCustomOrderBroadcast" />
            </intent-filter>
        </receiver>

        <receiver
            android:name=".component.BroadcastReceiver.CustomMiddleBroadcast"
            android:enabled="true"
            android:exported="true"
          >
            <intent-filter android:priority="500">
                <action android:name="SendCustomOrderBroadcast" />
            </intent-filter>
        </receiver>
        <receiver
            android:name=".component.BroadcastReceiver.CustomLowerBroadcast"
            android:enabled="true"
            android:exported="true"
           >
            <intent-filter android:priority="100">
                <action android:name="SendCustomOrderBroadcast" />
            </intent-filter>
        </receiver>
  1. 有序广播,高优先级广播可以优先处理

public class CustomHightBrodcast extends BroadcastReceiver {
    public CustomHightBrodcast() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("SendCustomOrderBroadcast")) {
            Toast.makeText(context, intent.getStringExtra("str_order_broadcast"), Toast.LENGTH_SHORT).show();
            Bundle bundle=new Bundle();
            bundle.putString("str_order_broadcast","经理说:公司每人发 5 个 月饼");
//            修改广播传输数据
            setResultExtras(bundle);
        }
    }
}
  1. 中优先级的广播后序处理

public class CustomMiddleBroadcast extends BroadcastReceiver {
    public CustomMiddleBroadcast() {
    }
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("SendCustomOrderBroadcast")) {
            Toast.makeText(context, getResultExtras(true).getString("str_order_broadcast"), Toast.LENGTH_SHORT).show();
            Bundle bundle=new Bundle();
            bundle.putString("str_order_broadcast","主管说:公司每人发 2 个 月饼");
            setResultExtras(bundle);
        }
    }
}
  1. 低优先级广播最后处理

public class CustomLowerBroadcast extends BroadcastReceiver {
    public CustomLowerBroadcast() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("SendCustomOrderBroadcast")) {
            String notice= getResultExtras(true).getString("str_order_broadcast");
            Toast.makeText(context,notice, Toast.LENGTH_SHORT).show();
//          终止广播继续传播下去
            abortBroadcast();
        }
    }
}

注意 :

  • 1.声明使用权限

 <!-- 申请使用自定义 有序广播的权限 -->
 <uses-permission >   android:name="android.permission.ORDERBROADCAST" />
  • 2.声明权限

 <!-- 自定义 有序广播的权限 -->
 <permission>
android:name="android.permission.ORDERBROADCAST"/>

在有序广播中高优先级的广播接收广播,可以修改数据,然后传给低优先级的广播。

3.发送持续广播(已经被弃用)

粘性广播会在Android系统中一直存在,不过随着 Android系统的不断更新,此方法逐渐被抛弃,使用方法如下:sendStickyBroadcast(intent);

5.广播接收(系统广播、自定义广播)

当广播发出后,如何接收广播呢,下面将介绍接收广播的方法。BroadcastReceiver,然后在onReceive方法,过滤广播Action中携带的Intent,然后进行相关处理。

接收开机广播的方法

1. 实现BootReceiverMethod 继承 BroadcastReceiver
p ublic class BootReceiverMethod extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //   接收开机广播处理事情,比如启动服务
        Intent mStartIntent = new Intent(context, StartServiceMethods.class);
        context.startService(mStartIntent);
    }
}
2.在Androidmainfest.xml 声明组件信息,并过滤开机完成 Action
        <receiver
            android:name=".component.BroadcastReceiver.BootReceiverMethod"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
3.声明接收开机广播完成的权限
   <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

640?wx_fmt=jpeg

640?wx_fmt=jpeg

长按识别二维码,领福利

至此,本篇已结束,如有不对的地方,欢迎您的建议与指正。同时期待您的关注,感谢您的阅读,谢谢!

如有侵权,请联系小编,小编对此深感抱歉,届时小编会删除文章,立即停止侵权行为,请您多多包涵。

为您每个 “在看”  而怦然心动640?wx_fmt=gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员Android

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值