您好!欢迎来到源码码网

Android BroadcastReceiver:接收广播

  • 源码教程
  • 来源:源码码网
  • 编辑:admin
  • 时间:2021-01-13 17:49
  • 阅读:579

广播(Broadcast)是 Android 系统中应用程序间通信的手段。

当有特定事件发生时,例如有来电、有短信、电池电量变化等事件发生时,Android 系统都会产生特定的 Intent 对象并且自动进行广播,而针对特定事件注册的 BroadcastReceiver 会接收到这些广播,并获取 Intent 对象中的数据进行处理。

在广播 Intent对象时可以指定用户权限,以此限制仅有获得了相应权限的 BroadcastReceiver 才能接收并处理对应的广播。

BroadcastReceiver 有动态和静态两种注册方法。

  • 动态注册方法即使用 Context. registerReceiver() 方法进行注册,需要特别注意的是,动态注册方法在退出程序前要使用 Context.unregisterReceiver() 方法撤销注册。

  • 静态注册方法即在 AndroidManifest.xml 文件中通过 <receiver> 标签进行注册。


一个 BroadcastReceiver 对象只有在被调用 onReceive(Context, Intent) 时才有效,当从该函数返回后,该对象就已无效了,其生命周期结束。

下面介绍如何使用动态注册来实现监听电池剩余电量。

实例 BatteryDemo 演示了使用动态注册 BroadcastReceiver 对象并且接收系统电量改变事件并加以处理的过程,运行效果如图 1 所示。

BatteryDemo的运行效果

图 1  BatteryDemo的运行效果

实例 BatteryDemo 中 main.xml 的代码如下:


  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3. android:layout_width="fill_parent"

  4. android:layout_height="fill_parent"

  5. android:orientation="vertical">


  6. <ToggleButton

  7. android:id="@+id/button"

  8. android:layout_width="fill_parent"

  9. android:layout_height="wrap_content"

  10. android:textOff="停止检测"

  11. android:textOn="检测当前手机电量" />


  12. <TextView

  13. android:id="@+id/text"

  14. android:layout_width="fill_parent"

  15. android:layout_height="wrap_content" />

  16. </LinearLayout>

实例 BatteryDemo 中 AndroidManifest.xml 的代码如下:


  1. <?xml version="1.0" encoding="utf-8"?>

  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"

  3. package="introduction.android.batterydemo"

  4. android:versionCode="1"

  5. android:versionName="1.0">


  6. <uses-sdk android:minSdkVersion="14" />

  7. <application

  8. android:allowBackup="true"

  9. android:icon="@mipmap/ic_launcher"

  10. android:label="@string/app_name"

  11. android:roundIcon="@mipmap/ic_launcher_round"

  12. android:supportsRtl="true"

  13. android:theme="@style/AppTheme">

  14. <activity android:name=".MainActivity">

  15. <intent-filter>

  16. <action android:name="android.intent.action.MAIN" />

  17. <category android:name="android.intent.category.LAUNCHER" />

  18. </intent-filter>

  19. </activity>

  20. </application>


  21. </manifest>

实例 BatteryDemo 中 MainActivity.java 的具体实现代码如下:


  1. package introduction.android.batterydemo;


  2. import android.content.BroadcastReceiver;

  3. import android.content.Context;

  4. import android.content.Intent;

  5. import android.content.IntentFilter;

  6. import android.support.v7.app.AppCompatActivity;

  7. import android.os.Bundle;

  8. import android.widget.CompoundButton;

  9. import android.widget.TextView;

  10. import android.widget.ToggleButton;


  11. import org.w3c.dom.Text;


  12. public class MainActivity extends AppCompatActivity {

  13. private ToggleButton button;

  14. private TextView text;

  15. BroadcastReceiver receiver = null;


  16. @Override

  17. protected void onCreate(Bundle savedInstanceState) {

  18. super.onCreate(savedInstanceState);

  19. setContentView(R.layout.activity_main);

  20. button = (ToggleButton) findViewById(R.id.button);

  21. text = (TextView) findViewById(R.id.text);


  22. final BroadcastReceiver receiver = new BroadcastReceiver() {

  23. @Override

  24. public void onReceive(Context context, Intent intent) {

  25. String action = intent.getAction();

  26. if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {

  27. int current = intent.getExtras().getInt("level");

  28. int total = intent.getExtras().getInt("scale");

  29. int value = current * 100 / total;

  30. text.setText("当前电量是" + value + "%" + "");

  31. }

  32. }

  33. };

  34. button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

  35. @Override

  36. public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

  37. if (isChecked) {

  38. IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

  39. registerReceiver(receiver, filter);

  40. } else {

  41. unregisterReceiver(receiver);

  42. text.setText("");


  43. }

  44. }

  45. });

  46. }

  47. }

其中,Intent.ACTION_BATTERY_CHANGED 为当电池电量变化时产生的 Intent 对象中携带的 Action 信息。

IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED) ;

用于确定当前 BroadcastReceiver 对象接收的 Intent 对象的类型。

下面是常用的方法:

  • registerReceiver(receiver, filter): 动态注册 receiver。

  • int current = intent.getExtras().getInt("level"): 获取当前电池的电量。

  • int total=intent.getExtras().getInt("scale"): 获取总电量。

  • unregisterReceiver(receiver):注销 receiver 注册。


该应用程序若要使用静态注册,则需要在 AndroidManifest.xml 文件中添加如下代码:

  1. <receiver android:name="receiver">

  2. <intent-filter>

  3. <action android:name="android.intent.action.BATTERY_CHANGED"/>

  4. </intent-filter>

  5. </receiver>


特别声明:
1、如无特殊说明,内容均为本站原创发布,转载请注明出处;
2、部分转载文章已注明出处,转载目的为学习和交流,如有侵犯,请联系客服删除;
3、编辑非《源码码网》的文章均由用户编辑发布,不代表本站立场,如涉及侵犯,请联系删除;
全部评论(0)
推荐阅读
  • 大型后台管理系统,用户登录状态该如何保存?
  • 大型后台管理系统,用户登录状态该如何保存?
  • 大型后台管理系统的用户登录状态保存需要综合考虑安全性、用户体验和系统架构。以下是企业级的完整方案:1.多层级存储策略class AuthManager {    constructor() {        this.storage = { &n
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-11-06 12:16
  • 阅读:350
  • 源码交易平台的支付困局与解决方案:如何通过专业支付系统提升交易效率
  • 源码交易平台的支付困局与解决方案:如何通过专业支付系统提升交易效率
  • 在数字经济蓬勃发展的今天,源码交易市场已成为互联网创业者和开发商的重要资源池。从电商系统源码到社交应用框架,从小程序解决方案到企业级管理系统,越来越多的开发者、初创企业和传统商家通过源码交易平台快速获取技术资产,实现商业目标的加速。源码交易市场的繁荣反映了数字化转型的迫切需求——企业需要快速迭代,开发者需要快速变现,用户需要快速启动。然而,在这个高速发展的市场中,一个长期被忽视但至关重要的问题浮现出来:支付系统的效率与安全性已成为制约交
  • 行业资讯
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-10-23 15:16
  • 阅读:298
  • Spring Boot 工程中 maven-surefire-plugin 测试执行失败及解决方法
  • Spring Boot 工程中 maven-surefire-plugin 测试执行失败及解决方法
  • 在SpringBoot工程编译时遇到maven-surefire-plugin的测试执行失败错误(Failedtoexecutegoalorg.apache.maven.plugins:maven-surefire-plugin:3.5.3:test),通常与测试环节相关。以下是常见原因及解决方法:1.测试用例执行失败• 原因:最常见的是测试用例(*Test.java)运行时抛出异常(如断言失败、空指针等),导
  • 源码教程
  • 来源:源码码网
  • 编辑:源码码网
  • 时间:2025-10-13 10:57
  • 阅读:363
  • WeMark - 微信小程序图片水印
  • WeMark - 微信小程序图片水印
  • 一个纯前端的微信小程序图片水印工具。支持文字/图片水印、单个与全屏两种模式,透明度与角度调节、单个水印位置X/Y控制,预览与对比模态、历史记录(100条)等功能。
  • 源码教程
  • 来源:源码码用户
  • 编辑:yg
  • 时间:2025-09-22 16:09
  • 阅读:287
联系客服
源码代售 源码咨询 素材咨询 联系客服
029-84538663
手机版

扫一扫进手机版
返回顶部