请选择 进入手机版 | 继续访问电脑版

Android 广播接收器(Broadcast Receivers)

[复制链接]

Android 广播接收器(Broadcast Receivers)

发表于 2021-12-28 13:51:06 只看大图 阅读模式 正序浏览
1002 0 查看全部
  广播接收器用于响应来自其他应用程序或者系统的广播消息。这些消息有时被称为事件或者意图。例如,应用程序可以初始化广播来让其他的应用程序知道一些数据已经被下载到设备,并可以为他们所用。这样广播接收器可以定义适当的动作来拦截这些通信。
  有以下两个重要的步骤来使系统的广播意图配合广播接收器工作。
  • 创建广播接收器
  • 注册广播接收器
  还有一个附加的步骤,要实现自定义的意图,你必须创建并广播这些意图。
创建广播接收器  广播接收器需要实现为BroadcastReceiver类的子类,并重写onReceive()方法来接收以Intent对象为参数的消息。
  1. public class MyReceiver extends BroadcastReceiver {
  2.    @Override
  3.    public void onReceive(Context context, Intent intent) {
  4.       Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
  5.    }
  6. }
复制代码
注册广播接收器  应用程序通过在AndroidManifest.xml中注册广播接收器来监听制定的广播意图。假设我们将要注册MyReceiver来监听系统产生的ACTION_BOOT_COMPLETED事件。该事件由Android系统的启动进程完成时发出。
broadcast.jpg
  1. ‹application
  2.    android:icon="@drawable/ic_launcher"
  3.    android:label="@string/app_name"
  4.    android:theme="@style/AppTheme" >
  5.    ‹receiver android:name="MyReceiver">

  6.       ‹intent-filter>
  7.          ‹action android:name="android.intent.action.BOOT_COMPLETED">
  8.          ‹/action>
  9.       ‹/intent-filter>

  10.    ‹/receiver>
  11. ‹/application>
复制代码
  现在,无论什么时候Android设备被启动,都将被广播接收器MyReceiver所拦截,并且在onReceive()中实现的逻辑将被执行。
  有许多系统产生的事件被定义为类Intent中的静态常量值。下面的表格列举了重要的系统事件。
事件常量描述
android.intent.action.BATTERY_CHANGED持久的广播,包含电池的充电状态,级别和其他信息。
android.intent.action.BATTERY_LOW标识设备的低电量条件。
android.intent.action.BATTERY_OKAY标识电池在电量低之后,现在已经好了。
android.intent.action.BOOT_COMPLETED在系统完成启动后广播一次。
android.intent.action.BUG_REPORT显示报告bug的活动。
android.intent.action.CALL执行呼叫数据指定的某人。
android.intent.action.CALL_BUTTON用户点击"呼叫"按钮打开拨号器或者其他拨号的合适界面。
android.intent.action.DATE_CHANGED日期发生改变。
android.intent.action.REBOOT设备重启。广播自定义意图  如果你想要应用程序中生成并发送自定义意图,你需要在活动类中通过sendBroadcast()来创建并发送这些意图。如果你使用sendStickyBroadcast(Intent)方法,则意图是持久的(sticky),这意味着你发出的意图在广播完成后一直保持着。
  1. public void broadcastIntent(View view)
  2. {
  3.    Intent intent = new Intent();
  4.    intent.setAction("com.runoob.CUSTOM_INTENT");
  5.    sendBroadcast(intent);
  6. }
复制代码
  com.runoob.CUSTOM_INTENT的意图可以像之前我们注册系统产生的意图一样被注册。
  1. ‹application
  2.    android:icon="@drawable/ic_launcher"
  3.    android:label="@string/app_name"
  4.    android:theme="@style/AppTheme" >
  5.    ‹receiver android:name="MyReceiver">

  6.       ‹intent-filter>
  7.          ‹action android:name="com.runoob.CUSTOM_INTENT">
  8.          ‹/action>
  9.       ‹/intent-filter>

  10.    ‹/receiver>
  11. ‹/application>
复制代码
实例  这个实例将解释如何创建广播接收器来拦截自定义意图。一旦你熟悉自定义意图,你可以为应用程序编程来拦截系统产生的意图。让我们按照下面的步骤来修改Hello World实例章节中我们创建的Android应用程序。
步骤描述
1使用Android Studio来创建Android应用程序并命名为broadcastreceiver,并放在Hello World实例章节中的com.runoob.broadcastreceiver包下。
2修改主要活动文件MainActivity.java来添加broadcastIntent()方法。
3在com.runoob.broadcastreceiver包下创建名为MyReceiver.java的新的Java文件来定义广播接收器。
4应用程序可以处理一个或多个自定义或者系统的意图,没有任何限制。每个你想拦截的意图都需要使用‹receiver.../>标签在AndroidManifest.xml中注册。
5修改res/layout/activity_main.xml文件中的默认内容来包含一个广播意图的按钮。
6不需要修改字符串文件,Android Studio会注意string.xml文件。
7启动Android模拟器来运行应用程序,并验证应用程序所做改变的结果。  下面是修改的主要活动文件src/com.runoob.broadcastreceiver/MainActivity.java的内容。这个文件包含了每个基础的生命周期方法。我们添加了broadcastIntent()方法来广播自定义事件。
  1. package com.runoob.broadcastreceiver;

  2. import android.os.Bundle;
  3. import android.app.Activity;
  4. import android.view.Menu;
  5. import android.content.Intent;
  6. import android.view.View;

  7. public class MainActivity extends Activity {

  8.     @Override
  9.     public void onCreate(Bundle savedInstanceState) {
  10.         super.onCreate(savedInstanceState);
  11.         setContentView(R.layout.activity_main);
  12.     }

  13.     @Override
  14.     public boolean onCreateOptionsMenu(Menu menu) {
  15.         getMenuInflater().inflate(R.menu.menu_main, menu);
  16.         return true;
  17.     }

  18.     // 广播自定义意图
  19.     public void broadcastIntent(View view){
  20.         Intent intent = new Intent();
  21.         intent.setAction("cn.programmer.CUSTOM_INTENT");
  22.         sendBroadcast(intent);
  23.     }
  24. }
复制代码
  下面是src/com.runoob.broadcastreceiver/MyReceiver.java的内容:
  1. package com.runoob.broadcastreceiver;

  2. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.widget.Toast;

  6. public class MyReceiver extends BroadcastReceiver {
  7.     @Override
  8.     public void onReceive(Context context, Intent intent) {
  9.         Toast.makeText(context, "检测到意图。", Toast.LENGTH_LONG).show();
  10.     }
  11. }
复制代码
  接下来修改AndroidManifest.xml文件。这里通过添加‹receiver.../>标签来包含我们的广播接收器:
  1. ‹?xml version="1.0" encoding="utf-8"?>
  2. ‹manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3.     package="com.runoob.broadcastreceiver"
  4.     android:versionCode="1"
  5.     android:versionName="1.0" >

  6.     ‹uses-sdk
  7.         android:minSdkVersion="8"
  8.         android:targetSdkVersion="22" />

  9.     ‹application
  10.         android:icon="@drawable/ic_launcher"
  11.         android:label="@string/app_name"
  12.         android:theme="@style/AppTheme" >

  13.         ‹activity
  14.             android:name=".MainActivity"
  15.             android:label="@string/title_activity_main" >

  16.             ‹intent-filter>
  17.                 ‹action android:name="android.intent.action.MAIN" />
  18.                 ‹category android:name="android.intent.category.LAUNCHER"/>
  19.             ‹/intent-filter>

  20.         ‹/activity>

  21.         ‹receiver android:name="MyReceiver">

  22.             ‹intent-filter>
  23.                 ‹action android:name="cn.programmer.CUSTOM_INTENT">
  24.                 ‹/action>
  25.             ‹/intent-filter>

  26.         ‹/receiver>

  27.     ‹/application>

  28. ‹/manifest>
复制代码
  下面是res/layout/activity_main.xml文件的内容,包含广播自定义意图的按钮。
  1. ‹RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
  3.     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
  4.     android:paddingRight="@dimen/activity_horizontal_margin"
  5.     android:paddingTop="@dimen/activity_vertical_margin"
  6.     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

  7.     ‹TextView
  8.         android:id="@+id/textView1"
  9.         android:layout_width="wrap_content"
  10.         android:layout_height="wrap_content"
  11.         android:text="广播实例"
  12.         android:layout_alignParentTop="true"
  13.         android:layout_centerHorizontal="true"
  14.         android:textSize="30dp" />

  15.     ‹TextView
  16.         android:id="@+id/textView2"
  17.         android:layout_width="wrap_content"
  18.         android:layout_height="wrap_content"
  19.         android:text="www.runoob.com"
  20.         android:textColor="#ff87ff09"
  21.         android:textSize="30dp"
  22.         android:layout_above="@+id/imageButton"
  23.         android:layout_centerHorizontal="true"
  24.         android:layout_marginBottom="40dp" />

  25.     ‹ImageButton
  26.         android:layout_width="wrap_content"
  27.         android:layout_height="wrap_content"
  28.         android:id="@+id/imageButton"
  29.         android:src="@drawable/ic_launcher"
  30.         android:layout_centerVertical="true"
  31.         android:layout_centerHorizontal="true" />

  32.     ‹Button
  33.         android:layout_width="wrap_content"
  34.         android:layout_height="wrap_content"
  35.         android:id="@+id/button2"
  36.         android:text="广播意图"
  37.         android:onClick="broadcastIntent"
  38.         android:layout_below="@+id/imageButton"
  39.         android:layout_centerHorizontal="true" />

  40. ‹/RelativeLayout>
复制代码
  下面是res/values/strings.xml文件的内容,定义了两个新的常量。
  1. ‹?xml version="1.0" encoding="utf-8"?>
  2. ‹resources>

  3.     ‹string name="app_name">Android Broadcast Receiver‹/string>
  4.     ‹string name="action_settings">Settings‹/string>
  5.     ‹string name="menu_settings">Settings‹/string>
  6.     ‹string name="title_activity_main">Main Activity‹/string>

  7. ‹/resources>
复制代码
  让我们运行刚刚修改的Hello World!应用程序。我假设你已经在安装环境时创建了AVD。打开你的项目中的活动文件,点击工具栏中的 eclipse_run.png 图标来在Android Studio中运行应用程序。Android Studio在AVD上安装应用程序并启动它。如果一切顺利,将在模拟器窗口上显示如下:
android_broadcast_receiver_1-1.png
  现在点击"广播意图"按钮来广播我们的自定义意图。这将广播我们的自定义意图"cn.programmer.CUSTOM_INTENT",在我们注册的广播接收器MyReceiver中拦截并执行我们实现的逻辑。模拟器的底部将出现toast。如下:
android_broadcast_receiver_2-1.png
  你可以尝试实现其他的广播接收器来拦截系统产生的意图,如系统启动,日期改变和低电量等。

来源:菜鸟教程
回复

使用道具 举报

游客~
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|极客同行 ( 蜀ICP备17009389号-1 )

© 2013-2016 Comsenz Inc. Powered by Discuz! X3.4