Android BroadcastReceiver示例教程

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 booting

    android.intent.action.BOOT_COMPLETED :系统完成启动后,将广播一次
  3. android.intent.action.CALL : To perform a call to someone specified by the data

    android.intent.action.CALL :对数据指定的某人执行呼叫
  4. android.intent.action.DATE_CHANGED : The date has changed

    android.intent.action.DATE_CHANGED :日期已更改
  5. android.intent.action.REBOOT : Have the device reboot

    android.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() {
    }
 
    @Override
    public 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">

    <Button
        android: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;

    @Override
    protected 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");

    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);

    }

    @Override
    protected 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" />

    <application
        android: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 {
    @Override
    public 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.

android broadcast receiver app

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

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

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值