今天我们将讨论并实现Android BroadcastReceiver,它是Android Framework中非常重要的组件。
Android BroadcastReceiver是android的一个休眠组件,用于监听系统范围的广播事件或intents。当发生任何这些事件时,它会通过创建状态栏通知或执行任务来使应用程序启动。与 Activity 不同,AndroidBroadcastReceiver
不包含任何用户界面。广播接收器通常被实现为根据接收到的意图数据的类型将任务委托给服务。以下是一些重要的系统范围内生成的意图。
-
android.intent.action.BATTERY_LOW:表示设备电池电量不足。
-
android.intent.action.BOOT_COMPLETED:系统启动完成后广播一次
-
android.intent.action.CALL:对数据指定的人进行呼叫
-
android.intent.action.DATE_CHANGED: 日期已更改
-
android.intent.action.REBOOT:让设备重新启动
-
android.net.conn.CONNECTIVITY_CHANGE:移动网络或wifi连接被更改(或重置)
要在 Android 应用程序中设置广播接收器,我们需要执行以下两件事。
- 创建广播接收器
- 注册广播接收器
让我们快速实现一个自定义的 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();
}
}
广播接收器是一个抽象类与onReceiver()
方法是抽象的。这onReceiver()
当任何事件发生时,首先在注册的广播接收器上调用该方法。意图对象与所有附加数据一起传递。 Context 对象也可用,用于启动活动或服务context.startActivity(myIntent);
or context.startService(myService);
分别。
BroadcastReceiver 可以通过两种方式注册。
- 通过将其定义在
AndroidManifest.xml
文件如下图所示。
<receiver android:name=".ConnectionReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
使用意图过滤器,我们告诉系统任何与我们的子元素匹配的意图都应该传递到特定的广播接收器。3。通过以编程方式定义它
以下代码片段显示了以编程方式注册广播接收器的示例。
IntentFilter filter = new IntentFilter();
intentFilter.addAction(getPackageName() + "android.net.conn.CONNECTIVITY_CHANGE");
MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);
取消注册广播接收器onStop()
or onPause()
对于该活动,可以使用以下代码片段。
@Override
protected void onPause() {
unregisterReceiver(myReceiver);
super.onPause();
}
以下代码片段用于向所有相关的 BroadcastReceiver 发送意图。
Intent intent = new Intent();
intent.setAction("com.journaldev.CUSTOM_INTENT");
sendBroadcast(intent);
不要忘记在清单的意图过滤器标记中或以编程方式添加上述操作。让我们开发一个应用程序来侦听网络更改事件以及自定义意图并相应地处理数据。
The 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
下面给出。
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);
}
}
在上面的代码中,我们以编程方式注册了另一个自定义操作。 ConnectionReceiver 定义在AndroidManifest.xml
文件如下。
<?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>
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. 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. 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项目