BroadCastReceiver,直译过来就是广播接收者,是Android四大基本组件之一,BroadCastReceiver本质上就是一个全局的监听器,用于监听系统全局的广播消息,它可以接收来自系统和应用的的广播。BroadCastReceiver一般用于接收通过sendBroadCast()方法发出去的Broadcast intents。
BroadcastReceiver的生命周期,从对象调用它开始,到onReceiver()方法执行完成之后结束。另外,每次广播被接收后会重新创建BroadcastReceiver对象,并在onReceiver方法中执行完就销毁,如果BroadcastReceiver的onReceiver方法中不能在10秒内执行完成,Android会出现ANR异常。所以不要在BroadcastReceiver的onReceiver方法中执行耗时的操作。
BroadCastReceiver有两种类型,分别是:
无序广播:是完全异步的可以同一时间被所有的接收者接收到的广播,缺点是:广播接受者不能将消息传递给下一个接受者,也不能终止消息的广播。
有序广播:有序广播的接收者按照一定的优先级进行消息的接收。如:A的优先级大于B的,B的优先级大于C的,那么消息先传递给A,当A的逻辑处理完成,再传递给B,B的逻辑处理完成,最后传递给C。优先级别声明在中,取值为[-1000,1000]数值越大优先级别越高。优先级也可通过filter.setPriority(10)方式设置。 另外有序广播的接收者可以通过abortBroadcast()的方式终止广播的传递,也可以通过setResultData和setResultExtras方法将处理的结果存入到BroadCast中,传递给下一个接收者。然后,下一个接收者通过getResultData()和getResultExtras(true)接收高优先级的接收者存入的数据。
第一步:创建需要启动的意图对象,即是Intent
第二步:调用Context.sendBroadcast()或sendOrderedBroadcast()方法来启动指定的广播接收者BroadcastReceiver。其中sendBroadcast()方法发送的是无序广播sendOrderedBroadcast()方法发送的是有序广播
发送广播的代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mReceiver = new SecondBroadCastReceiver();
btn_send1 = (Button) findViewById(R.id.btn_send1);
btn_send2 = (Button) findViewById(R.id.btn_send2);
btn_send1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("android.action.HelloBroadCastReceiver");
intent.putExtra("message", "这是发送的无序广播");
sendBroadcast(intent);
}
});
btn_send2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("android.action.SecondBroadCastReceiver");
intent.putExtra("message", "这是在发送有序的广播,你可以在广播中添加数据或者拦截广播");
sendOrderedBroadcast(intent, null);
}
});
IntentFilter intentFilter = new IntentFilter();
intentFilter.setPriority(200);
intentFilter.addAction("android.action.SecondBroadCastReceiver");
this.registerReceiver(mReceiver, intentFilter);
}
第一步:创建一个类继承BroadCastReceiver,重写onReceive()方法。
代码如下:
package com.example.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by Devin on 2016/6/22.
*/
public class HelloBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getExtras().getString("message").toString();
Toast.makeText(context, "收到广播了" + message, Toast.LENGTH_LONG).show();
}
}
第二步:注册BoradCastReceiver,即是指定BroadCastReceiver能匹配的Intent,注册BroadCastReceiver的方式有两种:
第一种:静态注册,即是在AndroidManifest.xml文件中注册,通过这种方法注册的广播即使应用关闭,被相应事件触发,程序也会被系统调用运行
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcast">
<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>
<!-- 在AndroidManifest.xml文件中注册-->
<receiver android:name=".HelloBroadCastReceiver">
<intent-filter android:priority="100">
<action android:name="android.action.HelloBroadCastReceiver"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
</application>
</manifest>
第二种:动态注册,通过代码注册,通过这种方法注册的广播,会跟随Activity的销毁而销毁,所以我们需要在Activity的onDestroy()方法中调用unregisterReceiver(receiver)方法移除掉广播,必须要调用unregisterReceiver(receiver)方法,否则程序会出现异常。
IntentFilter intentFilter = new IntentFilter();
intentFilter.setPriority(200);
intentFilter.addAction("android.action.SecondBroadCastReceiver");
this.registerReceiver(mReceiver, intentFilter);
@Override
protected void onDestroy() {
super.onDestroy();
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
}
运行效果如下:
其中,IntentFilter是设置过滤的action和优先级,优先级高的可以优先接收到广播。需要在onDestroy中调用unregisterReceiver(mReceiver)方法。
前面介绍的发送广播都是在应用之间发送的,这样我们的APP发出的广播会被其它应用接收到,这样容易引起安全问题,所以,Android系统还提供了另外一种广播机制————本地广播
下面用一个简单的例子实现本地广播:
package com.example.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by Administrator on 2016/6/22.
*/
public class MYLocalBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getExtras().getString("message").toString();
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
Activity的代码
package com.example.broadcast;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
/**
* Created by Administrator on 2016/6/22.
*/
public class LocalBroadCastActivity extends AppCompatActivity {
MYLocalBroadCastReceiver myLocalBroadCastReceiver;
LocalBroadcastManager localBroadcastManager;
Button btn_send_local;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_local);
localBroadcastManager = LocalBroadcastManager.getInstance(LocalBroadCastActivity.this);
myLocalBroadCastReceiver = new MYLocalBroadCastReceiver();
btn_send_local = (Button) findViewById(R.id.btn_send_local);
btn_send_local.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("android.intent.action.MYLocalBroadCastReceiver");
intent.putExtra("message", "接收到本地广播啦");
localBroadcastManager.sendBroadcast(intent);
}
});
IntentFilter intentFilter = new IntentFilter();
intentFilter.setPriority(200);
intentFilter.addAction("android.intent.action.MYLocalBroadCastReceiver");
localBroadcastManager.registerReceiver(myLocalBroadCastReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (localBroadcastManager != null) {
if (myLocalBroadCastReceiver != null) {
localBroadcastManager.unregisterReceiver(myLocalBroadCastReceiver);
}
}
}
}
效果图如下:
关于BroadCastReceiver的介绍就到这里