broadcastreceiver基本使用

安辉就是我 安辉就是我     2022-08-22     175

关键词:

Broadcast Receiver介绍

Broadcast Receiver翻译成中文叫“广播接收器”,所以它的作用是用来接收发送过来的广播的。

Android应用程序可以发送或接收来自Android系统和其他Android应用程序的广播消息,类似于发布订阅设计模式。当有兴趣的事件发生时发送这些广播。例如,Android系统在各种系统事件发生时发送广播,例如当系统启动或设备开始充电时。应用程序也可以发送自定义广播,例如,通知其他应用程序的东西,他们可能感兴趣(例如,一些新的数据已被下载)。应用程序可以注册接收特定的广播。当发送广播时,系统自动将广播路由到订阅该特定类型广播的应用程序。
一般来说,广播可以作为跨应用程序和正常用户流之外的消息传递系统。

动态注册广播

动态注册广播是一种灵活的注册方式,通过代码来注册广播,销毁广播。

首先我们新建DynamicBroadcast类,继承自BroadcastReceiver,用来接收广播,重写onReceive方法,通过intent可以获取发送广播时传入的参数。

public class DynamicBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent){
        String data = intent.getStringExtra("data");
        Log.i("data",data);
    }
}

在activity_main.xml文件中增加一个按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/btn_dynamic_broadcast_send_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="给动态注册的广播发送消息"/>
</LinearLayout>

最后我们下来看MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    public static final String ACTION_DYNAMIC_BROADCAST="android.intent.action.DYNAMIC_BROADCAST";
    private DynamicBroadcast dynamicBroadcast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_dynamic_broadcast_send_message).setOnClickListener(this);

        //动态注册广播
        dynamicBroadcast=new DynamicBroadcast();
        IntentFilter intentFilter=new IntentFilter(ACTION_DYNAMIC_BROADCAST);
        registerReceiver(dynamicBroadcast,intentFilter);
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn_dynamic_broadcast_send_message:
                Intent intent = new Intent(ACTION_DYNAMIC_BROADCAST);
                intent.putExtra("data","Dynamic Broadcast Parameter");//通过intent传参
                sendBroadcast(intent);//发送广播消息
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("MainActivity onDestroy","销毁广播");
        unregisterReceiver(dynamicBroadcast);
    }
}

我们在onCreate中通过registerReceiver方法注册一个广播,需要两个参数(BroadcastReceiver跟IntentFilter对象)。同时给”发送广播”按钮设置点击监听,点击之后通过sendBroadcast方法发送广播,这里需要一个Intent对象,构造Intent对象的时候传入Action,这个Action跟我们注册广播的时候Action要一致。

我们还重写了onDestroy方法,当Activity销毁的时候同时销毁广播,所以,在本例中,广播的生命周期跟Activity一样。

我们运行代码,点击”给动态注册的广播发送消息”按钮,Log打印如下:

02-03 16:32:11.194 7095-7095/com.ansen.broadcastreceiver I/data: Dynamic Broadcast Parameter

静态注册广播

静态注册广播是在AndroidManifest.xml文件中注册的,无论这个程序是否启动,当收到广播时,都会接收的到。

我们在动态注册广播的Demo上增加代码,新建StaticBroadcast类,继承BroadcastReceiver,实现onReceive方法,跟动态广播的接收器代码几乎一样。

public class StaticBroadcast extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent){
        String data = intent.getStringExtra("data");
        Log.i("data",data);
    }
}

接下来我们需要在AndroidManifest.xml文件中注册这个广播,通过receiver标签的name属性指定这个类,再增加intent-filter标签,给action标签设置name属性值,我们发送广播的时候需要用到这个值。

<receiver android:name=".StaticBroadcast" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.STATIC_BROADCAST"/>
    </intent-filter>
</receiver>

在activity_main.xml文件中增加一个按钮,”给静态注册的广播发送消息”。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/btn_dynamic_broadcast_send_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="给动态注册的广播发送消息"/>
    <Button
        android:id="@+id/btn_static_broadcast_send_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="给静态注册的广播发送消息"/>
</LinearLayout>

给按钮设置点击监听事件,在对应的onClick回掉方法中发送广播,我们看到Intent的构造方法有传入一个字符串,这个值跟我们在xml中receiver标签->intent-filter->action的name属性的值必须要一致。在广播底层源码中就是通过action来区分不同的广播接收者。

Intent staticIntent = new Intent("android.intent.action.STATIC_BROADCAST");
staticIntent.putExtra("data","Static Broadcast Parameter");//通过intent传参
sendBroadcast(staticIntent);//发送广播消息

因为没有增加很多代码,MainActivity的代码就不全部贴出来了,重新运行代码,点击“给静态注册的广播发送消息”按钮,打印的log如下:

02-06 14:02:38.735 10749-10749/com.ansen.broadcastreceiver I/data: Static Broadcast Parameter

广播基本总结

动态注册广播跟静态注册广播区别

前面我们写了Demo,也介绍了动态注册广播跟静态注册广播,这里我再来总结一下:
- 动态注册 广播的生命周期自己灵活控制,消耗资源少。
- 静态注册 广播一直存在,除非软件卸载。消耗资源稍微大一些。当然现在的手机硬件都跟的上了,这点资源可以忽略不计。

广播注意事项

我们都知道收到了广播就会执行onReceive方法,但是在这个方法里面不能做耗时超过10秒的事情,否则会弹出ANR(Application NoResponse)的对话框。如果有需要就另外启动一个Thread处理耗时操作。

LocalBroadcastManager解决BroadcastReceiver安全问题

LocalBroadcastManager是Android Support包提供了一个工具,是用来在同一个应用内的不同组件间发送Broadcast的
。可以解决BroadcastReceiver的安全问题(恶意程序脚本不断的去发送你所接收的广播)。

使用LocalBroadcastManager有以下好处:
- 发送的广播只会在自己App内传播,不会泄露给其他App,确保隐私数据不会泄露
- 其他App也无法向你的App发送该广播,不用担心其他App会来搞破坏
- 比系统全局广播更加高效

使用方法跟动态注册广播类似。首先需要获取LocalBroadcastManager对象,单例模式获取,然后调用registerReceiver方法。

broadcastManager = LocalBroadcastManager.getInstance(this);
localReceiver=new LocalBroadcastReceiver();
broadcastManager.registerReceiver(localReceiver,new IntentFilter(ACTION_LOCAL_BROADCAST));

发送广播也类似。这里一定需要调用LocalBroadcastManager对象的sendBroadcast方法发送广播哦,不然接收不到广播

Intent localIntent=new Intent(ACTION_LOCAL_BROADCAST);
localIntent.putExtra("data","Local Broadcast Parameter");//通过intent传参
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);

顺便在onDestroy方法中取消注册。

@Override
protected void onDestroy(){
    super.onDestroy();
    Log.i("MainActivity onDestroy","销毁广播");
    unregisterReceiver(dynamicBroadcast);
    broadcastManager.unregisterReceiver(localReceiver);
}

因为跟动态注册广播类似,所以只贴出了关键代码。

源码下载

GCM 如何使用 BroadCastReceiver 处理应用程序

】GCM如何使用BroadCastReceiver处理应用程序【英文标题】:HowdoesGCMhandleappswithBroadCastReceiver【发布时间】:2015-08-0905:34:30【问题描述】:我很难理解&lt;intent-filter&gt;如何处理BroadCastReceiver的基本概念。使用下面的代码我设置了... 查看详情

android开发四大组件——broadcastreceiver基本使用介绍(代码片段)

...自己的广播接收类,代码如下:/***@authorbaorant*/publicclassMyBroadcastReceiver2 查看详情

Android requestLocationUpdates 使用 PendingIntent 和 BroadcastReceiver

】AndroidrequestLocationUpdates使用PendingIntent和BroadcastReceiver【英文标题】:AndroidrequestLocationUpdatesusingPendingIntentwithBroadcastReceiver【发布时间】:2011-12-1507:26:22【问题描述】:如何使用requestLocationUpdates(longminTime,floatminDis 查看详情

android基础到进阶面试题之broadcastreceiver使用+实例(代码片段)

BroadcastReceiver是什么        BroadcastReceiver是Android四大组件之一,是一种广泛运用在应用程序之间传输信息的机制,通过发送Intent来传送我们的数据。BroadcastReceiver使用场景应用内多个不同组件之间的消息通信。跨应用... 查看详情

ContentObserver 与 BroadCastReceiver:电池使用情况、内存、CPU?

】ContentObserver与BroadCastReceiver:电池使用情况、内存、CPU?【英文标题】:ContentObservervs.BroadCastReceiver:BatteryUsage,Ram,CPU?【发布时间】:2012-08-3120:35:11【问题描述】:由于对应用程序的电池使用、内存和cpu使用有如此必要的关注,... 查看详情

使用registerreceiver注册broadcastreceiver

publicIntentregisterReceiver(BroadcastReceiverreceiver,IntentFilterfilter):注册一个BroadcaseReceiver在主activity线程中运行,这个receiver只能够被主application线程中匹配filter的Intent唤醒执行;unregisterReceiver(receiver):注销receiver 查看详情

使用字符串资源命名(标记)小部件的 BroadcastReceiver

】使用字符串资源命名(标记)小部件的BroadcastReceiver【英文标题】:Usingastringresourcetoname(label)awidget\'sBroadcastReceiver【发布时间】:2020-01-1711:55:21【问题描述】:我有一个如下定义的小部件:[BroadcastReceiver(Label="Upcoming")][IntentFilte... 查看详情

java示例代码_使用BroadcastReceiver删除传入的Sms

java示例代码_使用BroadcastReceiver删除传入的Sms 查看详情

broadcastreceiver的使用,动态注册和注销,优先级和中断控制

BroadcastReceiver:BroadcastReceiver(广播接收器)是Android中的四大组件之一,用来通知某些事件的相关信息,如下载完成,设置改变等。 默认的BroadcastReceiver状态(新建完未更改任何设置)的简单使用方法:1.通过newIntnet(MainActivit... 查看详情

broadcastreceiver使用goasync执行异步操作

roadcastReceiver生命周期一个BroadcastReceiver对象只有在被调用onReceive(Context,Intent)的才有效的,当从该函数返回后,该对象就无效的了,结束生命周期。因此从这个特征可以看出,在所调用的onReceive(Context,Intent)函数里,不能有过于耗... 查看详情

GCM BroadcastReceiver setResultCode 使用

】GCMBroadcastReceiversetResultCode使用【英文标题】:GCMBroadcastReceiversetResultCodeuse【发布时间】:2014-07-0609:27:18【问题描述】:我正在使用来自android开发人员的GCM示例,但无法理解setResultCode(Activity.Result_OK)。哪个组件接收到这个消息... 查看详情

使用 AlarmManager/BroadcastReceiver 在 Android 中每周一重复闹钟

】使用AlarmManager/BroadcastReceiver在Android中每周一重复闹钟【英文标题】:RepeatAlarmsonEveryMondayinAndroidusingAlarmManager/BroadcastReceiver【发布时间】:2012-06-2509:23:55【问题描述】:我想在每周一上午09:00和下午05:00重复我的任务。我为此使... 查看详情

使用 BroadcastReceiver 询问用户是不是希望打开应用程序 onReceive

】使用BroadcastReceiver询问用户是不是希望打开应用程序onReceive【英文标题】:UseBroadcastReceiverthatasksauseriftheywishtoopenapponReceive使用BroadcastReceiver询问用户是否希望打开应用程序onReceive【发布时间】:2018-02-1913:52:14【问题描述】:我... 查看详情

使用 BroadcastReceiver 实现 Android 通知操作时出错

】使用BroadcastReceiver实现Android通知操作时出错【英文标题】:ErrorwhileimplementingAndroidNotificationActionswithBroadcastReceiver【发布时间】:2021-09-2815:03:00【问题描述】:我正在尝试让通知中的操作按钮调用一种方法。我阅读并关注了一些... 查看详情

broadcastreceiver庖丁解牛

本节引言:上节我们对BroadcastReceiver已经有了一个初步的了解了,知道两种广播类型:标准与有序,动态或静态注册广播接收者,监听系统广播,自己发送广播!已经满足我们的基本需求了~但是前面写的广播都是全局广播!这同... 查看详情

在 Main Activity 中使用 BroadcastReceiver 更新 Widget

】在MainActivity中使用BroadcastReceiver更新Widget【英文标题】:updatingWidgetusingBroadcastReceiverinMainActivity【发布时间】:2013-06-2520:09:43【问题描述】:我正在开发一个包含时钟的android小部件。到目前为止,我能够成功地将时钟设置为当... 查看详情

并不总是触发带有 BroadcastReceiver 的地理围栏

】并不总是触发带有BroadcastReceiver的地理围栏【英文标题】:GeofencewithBroadcastReceiverisnotalwaystriggered【发布时间】:2019-03-2611:34:29【问题描述】:在我的应用程序中使用地理围栏之前,我使用IntentService作为其回调,一切正常。但... 查看详情

adb shell 的 BroadcastReceiver 权限

】adbshell的BroadcastReceiver权限【英文标题】:BroadcastReceiverpermissionforadbshell【发布时间】:2016-05-0105:01:46【问题描述】:考虑一个使用BroadcastReceiver的简单工具来实现一个简单的目标。因为这不应该被其他应用程序使用,所以它定... 查看详情