Today we’ll discuss and implement Android BroadcastReceiver that is a very important component of Android Framework.

今天,我们将讨论和实现Android BroadcastReceiver,它是Android Framework的非常重要的组成部分。

Android BroadcastReceiver (Android BroadcastReceiver)

Android BroadcastReceiver is a dormant component of android that listens to system-wide broadcast events or intents.

Android BroadcastReceiver是android的Hibernate组件,它侦听系统范围的广播事件或Intent 。

When any of these events occur it brings the application into action by either creating a status bar notification or performing a task.

这些事件中的任何一个发生时,它都会通过创建状态栏通知或执行任务来使应用程序生效。

Unlike activities, android BroadcastReceiver doesn’t contain any user interface. Broadcast receiver is generally implemented to delegate the tasks to services depending on the type of intent data that’s received.

与活动不同,Android BroadcastReceiver不包含任何用户界面。 广播接收器通常实现为根据接收到的意图数据的类型将任务委托给服务。

Following are some of the important system wide generated intents.

以下是一些在系统范围内产生的重要意图。

  1. android.intent.action.BATTERY_LOW : Indicates low battery condition on the device.android.intent.action.BATTERY_LOW :指示设备的电池电量不足。
  2. android.intent.action.BOOT_COMPLETED : This is broadcast once, after the system has finished bootingandroid.intent.action.BOOT_COMPLETED :系统完成启动后,将广播一次
  3. android.intent.action.CALL : To perform a call to someone specified by the dataandroid.intent.action.CALL :对数据指定的某人执行呼叫
  4. android.intent.action.DATE_CHANGED : The date has changedandroid.intent.action.DATE_CHANGED :日期已更改
  5. android.intent.action.REBOOT : Have the device rebootandroid.intent.action.REBOOT :重启设备
  6. android.net.conn.CONNECTIVITY_CHANGE : The mobile network or wifi connection is changed(or reset)android.net.conn.CONNECTIVITY_CHANGE :移动网络或wifi连接已更改(或重置)

Android中的广播接收器 (Broadcast Receiver in Android)

To set up a Broadcast Receiver in android application we need to do the following two things.

要在android应用程序中设置广播接收器,我们需要做以下两件事。

  1. Creating a BroadcastReceiver创建一个BroadcastReceiver
  2. Registering a BroadcastReceiver注册广播接收器

创建一个BroadcastReceiver (Creating a BroadcastReceiver)

Let’s quickly implement a custom BroadcastReceiver as shown below.

让我们快速实现一个自定义的BroadcastReceiver,如下所示。

public class MyReceiver extends BroadcastReceiver {public MyReceiver() {}@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show();}
}

BroadcastReceiver is an abstract class with the onReceiver() method being abstract.

BroadcastReceiver是一个抽象类 ,其中onReceiver()方法是抽象的。

The onReceiver() method is first called on the registered Broadcast Receivers when any event occurs.

发生任何事件时,首先在已注册的广播接收器上调用onReceiver()方法。

The intent object is passed with all the additional data. A Context object is also available and is used to start an activity or service using context.startActivity(myIntent); or context.startService(myService); respectively.

意向对象与所有其他数据一起传递。 Context对象也是可用的,并用于使用context.startActivity(myIntent);启动活动或服务context.startActivity(myIntent);context.startService(myService); 分别。

在Android应用程序中注册BroadcastReceiver (Registering the BroadcastReceiver in android app)

A BroadcastReceiver can be registered in two ways.

可以通过两种方式注册BroadcastReceiver。

  1. By defining it in the AndroidManifest.xml file as shown below.通过在AndroidManifest.xml文件中定义它,如下所示。
  2. <receiver android:name=".ConnectionReceiver" ><intent-filter><action android:name="android.net.conn.CONNECTIVITY_CHANGE" /></intent-filter>
    </receiver>

    Using intent filters we tell the system any intent that matches our subelements should get delivered to that specific broadcast receiver.

    使用意图过滤器,我们告诉系统与子元素匹配的任何意图都应传递到该特定广播接收器。

  3. By defining it programmatically通过编程定义
  4. Following snippet shows a sample example to register broadcast receiver programmatically.

    下面的代码片段显示了一个示例示例,以编程方式注册广播接收器。

    IntentFilter filter = new IntentFilter();
    intentFilter.addAction(getPackageName() + "android.net.conn.CONNECTIVITY_CHANGE");MyReceiver myReceiver = new MyReceiver();
    registerReceiver(myReceiver, filter);

To unregister a broadcast receiver in onStop() or onPause() of the activity the following snippet can be used.

要在活动的onStop()onPause()中注销广播接收器,可以使用以下代码段。

@Override
protected void onPause() {unregisterReceiver(myReceiver);super.onPause();
}

从活动发送广播意图 (Sending Broadcast intents from the Activity)

The following snippet is used to send an intent to all the related BroadcastReceivers.

以下代码段用于向所有相关的BroadcastReceivers发送意图。

Intent intent = new Intent();intent.setAction("com.journaldev.CUSTOM_INTENT");sendBroadcast(intent);

Don’t forget to add the above action in the intent filter tag of the manifest or programmatically.

不要忘记在清单的意图过滤器标签中或以编程方式添加以上操作。

Let’s develop an application that listens to network change events and also to a custom intent and handles the data accordingly.

让我们开发一个应用程序,该应用程序侦听网络更改事件以及自定义意图并相应地处理数据。

Android项目结构中的BroadcastReceiver (BroadcastReceiver in Android Project Structure)

Android BroadcastReceiver代码 (Android BroadcastReceiver Code)

The activity_main.xml consists of a button at the centre that sends a broadcast intent.

activity_main.xml包含一个位于中心的按钮,用于发送广播意图。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:tools="https://schemas.android.com/tools"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.journaldev.broadcastreceiver.MainActivity"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/button"android:text="Send Broadcast"android:layout_centerVertical="true"android:layout_centerHorizontal="true" />
</RelativeLayout>

The MainActivity.java is given below.

MainActivity.java在下面给出。

package com.journaldev.broadcastreceiver;import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;public class MainActivity extends AppCompatActivity {ConnectionReceiver receiver;IntentFilter intentFilter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ButterKnife.inject(this);receiver = new ConnectionReceiver();intentFilter = new IntentFilter("com.journaldev.broadcastreceiver.SOME_ACTION");}@Overrideprotected void onResume() {super.onResume();registerReceiver(receiver, intentFilter);}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(receiver);}@OnClick(R.id.button)void someMethod() {Intent intent = new Intent("com.journaldev.broadcastreceiver.SOME_ACTION");sendBroadcast(intent);}
}

In the above code we’ve registered another custom action programmatically.

在上面的代码中,我们以编程方式注册了另一个自定义操作。

The ConnectionReceiver is defined in the AndroidManifest.xml file as below.

如下所示,在AndroidManifest.xml文件中定义了ConnectionReceiver。

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"package="com.journaldev.broadcastreceiver"><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><receiver android:name=".ConnectionReceiver"><intent-filter><action android:name="android.net.conn.CONNECTIVITY_CHANGE" /></intent-filter></receiver></application>
</manifest>

The ConnectionReceiver.java class is defined below.

下面定义了ConnectionReceiver.java类。

public class ConnectionReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Log.d("API123",""+intent.getAction());if(intent.getAction().equals("com.journaldev.broadcastreceiver.SOME_ACTION"))Toast.makeText(context, "SOME_ACTION is received", Toast.LENGTH_LONG).show();else {ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetwork = cm.getActiveNetworkInfo();boolean isConnected = activeNetwork != null &&activeNetwork.isConnectedOrConnecting();if (isConnected) {try {Toast.makeText(context, "Network is connected", Toast.LENGTH_LONG).show();} catch (Exception e) {e.printStackTrace();}} else {Toast.makeText(context, "Network is changed or reconnected", Toast.LENGTH_LONG).show();}}}}

In the above code we check the intent action that triggers the onReceive() method and based on that display the toast.

在上面的代码中,我们检查意图触发触发onReceive()方法的意图操作,并基于该意图显示吐司。

Note: To make the broadcast receiver unavailable to external applications, add the attribute android:exported=false in the manifest. When we send a broadcast, it is possible for the external applications too to receive them. This can be prevented by specifying this limitation.

注意 :要使广播接收器无法用于外部应用程序,请在清单中添加属性android:exported=false 。 当我们发送广播时,外部应用程序也有可能接收它们。 通过指定此限制可以防止这种情况。

The output app in action is given below.

运行中的输出应用程序如下所示。

This brings an end android BroadcastReceiver tutorial. You can download the final BroadcastReceivers project from the link below.

这就结束了android BroadcastReceiver教程。 您可以从下面的链接下载最终的BroadcastReceivers项目。

Download Android BroadcastReceiver Project下载Android BroadcastReceiver项目

翻译自: https://www.journaldev.com/10356/android-broadcastreceiver-example-tutorial

Android BroadcastReceiver示例教程相关推荐

  1. Android WebView示例教程

    Android WebView is used to display HTML in an android app. We can use android WebView to load HTML p ...

  2. Android ExpandableListView示例教程

    Welcome to Android ExpandableListView Example Tutorial. In this tutorial we'll implement an Expandab ...

  3. Android ListView示例教程

    We will learn how to create a simple Android ListView and launch a new activity on selecting a singl ...

  4. Android ActionBar示例教程

    Today we will look into Android ActionBar. Action Bar is one of the important part of any applicatio ...

  5. Android ViewPager示例教程

    ViewPager in Android allows the user to flip left and right through pages of data. In our android Vi ...

  6. 使用DataBinding的Android SearchView示例教程

    Today we will look into Android SearchView widget and develop an application that filters a ListView ...

  7. Android AsyncTask示例教程

    Today we will look into Android AsyncTask. We will develop an Android example application that perfo ...

  8. android jni示例_Android动画示例

    android jni示例 Android Animation is used to give the UI a rich look and feel. Animations in android a ...

  9. Android ProgressDialog示例

    Welcome to Android ProgressDialog Example. In this tutorial we'll learn how to create Android Progre ...

最新文章

  1. 关于OpenGL ES 3D 光晕如何产生的自我理解
  2. 如何接入虹软免费人脸识别SDK
  3. Docker Hub 镜像加速器
  4. js贪心算法---背包问题
  5. BZOJ 4155 Humble Captains
  6. php 入库乱码,php 中文字符入库或显示乱码问题的解决方法_PHP教程
  7. 产品选型“神器” TIA Selection Tools 之选择 S7-1500T 全程详解
  8. 2019-2020年数学建模竞赛心得体会
  9. 存储之磁盘阵列RAID
  10. CAN bus 基础知识
  11. java 夏令时_Java里面的夏令时
  12. 戴尔计算机更新程序,戴尔电脑如何更新显卡驱动 其实很简单-电脑显卡怎么升级...
  13. §1.1自然数 上•序数理论
  14. BAT都怎么泡区块链?假醉网易,炮灰百度,闷骚腾讯,假正经阿里
  15. 使用expdp和impdp导出导入本地oracle数据.dmp文件
  16. ORACLE违反协议异常
  17. 【财富空间】毛日昇:阿里“五新”战略有力助推供给侧结构性改革
  18. K12在线教育行业现状与发展前景分析
  19. Socket搭建即时通讯服务器
  20. java 生成证书 android_Android自有证书生成指南

热门文章

  1. Visual Studio 单元测试之二---顺序单元测试
  2. [转载] python中的Numpy库入门
  3. 2019/3/14 软工作业
  4. java中的interface
  5. 拷贝data/data/包名/files文件记下所有文件及文件夹到本地sdcard根目录teddyData_files文件夹下...
  6. 《A.I.爱》王力宏与人工智能谈恋爱 邀李开复来客串
  7. 机器学习(三)——决策树(decision tree)算法介绍
  8. 读美国教授写给被开除中国留学生的信感悟
  9. BSD Socket~TCP~Example Code
  10. 兔子--html,js,php,ASP,ASP.NET,JSP的关系