BroadcastReceiver简介
BroadcastReceiver是Android四大嫡系组件之一。它的功能非常强大,专门应用于接收广播消息通知,提醒用户做出处理。比如低电量提醒、时区改变提醒、语言选项改变提醒……
Android中的广播事件有下面5种:
1.Normal Broadcast:普通广播
2.System Broadcast: 系统广播(如ACTION_BATTERY_LOW)
3.Ordered broadcast:有序广播
4.Sticky Broadcast:粘性广播(在 android 5.0中deprecated)
5.Local Broadcast:App应用内广播
如何注册广播
注册广播得方式有两种:
1.静态注册
即在清单文件中进行注册广播
<receiver android:name=".MyBroadcastReceiver">
<intent-filter >
<action android:name="com.robinsyu"/>
</intent-filter>
</receiver>
2.动态注册
即在Java代码中注册广播
MyReceiver receiver=new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.robinsyu");
如何发送广播
通过intent传递注册的Action,使用sendBroadcast方法发送广播
Intent intent=new Intent();
intent.setAction("com.robinsyu");
intent.putExtra("name","I love android");
sendBroadcast(intent);
如何接收广播
1.首先要写一个广播接收器类,该类从BroadcastReceiver继承。
2.在onReceive方法中编写处理广播的代码
3.注意不要忘记在AndroidManifest.xml注册
如果一个广播接收器需要处理多个广播,可以使用intent.getAction方法判断当前接收到的是哪一个广播。
if ("action1".equals(intent.getAction())){
//TODO……
} else if("action2".equals(intent.getAction())){
//TODO……
}
Demo1:有序广播与无序广播
【1】无序广播:所有的接收者都会接收事件,不可以被拦截和修改。
【2】有序广播:按照优先级向下传递,可以修改广播数据和终止广播事件。
这里介绍一个有序广播的例子
1.编写三个BroadcastReceiver子类并在AndroidManifest.xml文件注册
分别设置优先级为-1000(最低),0(中间),1000(最高)
<receiver android:name=".MyBroadcast1">
<!-- 定义广播的优先级 -->
<intent-filter android:priority="-1000">
<action android:name="com.robinsyu"></action>
</intent-filter>
</receiver>
<receiver android:name=".MyBroadcast2">
<!-- 定义广播的优先级 -->
<intent-filter android:priority="0">
<action android:name="com.robinsyu"></action>
</intent-filter>
</receiver>
<receiver android:name=".MyBroadcast3">
<!-- 定义广播的优先级 -->
<intent-filter android:priority="1000">
<action android:name="com.robinsyu"></action>
</intent-filter>
</receiver>
2.在布局中添加一个按钮,设置其点击事件为发送有序广播
public void onClick(View view){
switch (view.getId()){
case R.id.btn_sendbroad:
Intent intent=new Intent();
intent.putExtra("msg","有序广播");
intent.setAction("com.robinsyu");
/**
* @param permition:设置接收有序广播的条件,没有条件为null
*/
sendOrderedBroadcast(intent,null);
break;
}
}
3.在onReceive方法中接收广播消息
MyBroadcast1.java
public class MyBroadcast1 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,intent.getStringExtra("msg")+"MyBroadcast1",Toast.LENGTH_SHORT).show();
}
}
MyBroadcast2.java
public class MyBroadcast2 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,intent.getStringExtra("msg")+"MyBroadcast2",Toast.LENGTH_SHORT).show();
}
}
MyBroadcast3.java
public class MyBroadcast3 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,intent.getStringExtra("msg")+"MyBroadcast3",Toast.LENGTH_SHORT).show();
}
}
Demo2:使用BroadcastReceiver获取短信内容
1.在AndroidManifest.xml文件中注册receiver
<receiver
android:name=".ShortMessageReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
2.在AndroidManifest.xml文件中添加权限
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
3.java代码:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
public class ShortMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null){
Object[] objArray = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[objArray.length];
for (int i=0; i<objArray.length; i++){
byte[] pdus = (byte[]) objArray[i];
messages[i] = SmsMessage.createFromPdu(pdus);
String content = messages[i].getMessageBody();
String phone = messages[i].getOriginatingAddress();
Log.i("robinsyu","手机号码为:" + phone +"***" + "短信内容为:" + content);
}
}
}
}
Demo3: 使用BroadCastReceiver拦截骚扰电话
1.在AndroidManifest.xml文件中注册receiver
<receiver
android:name=".BlockCallReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
2.在AndroidManifest.xml文件中声明权限
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
3.java代码:
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BlockCallReceiver extends BroadcastReceiver {
private final static String BLACKLIST_NUMBER = "10086";
@Override
public void onReceive(Context context, Intent intent) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
switch (tm.getCallState()) {
case TelephonyManager.CALL_STATE_RINGING:
String incomingNumber = intent.getStringExtra("incoming_number");
if (BLACKLIST_NUMBER.equals(incomingNumber)) {
Class<TelephonyManager> telephonyManagerClass = TelephonyManager.class;
try {
//使用Java反射获取getITelephony方法对应的Method对象
Method telephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony", null);
telephonyMethod.setAccessible(true);
Object object = telephonyMethod.invoke(tm,null);
//使用Java反射技术获取与endCall方法对应的Method对象
Method endCallMethod = object.getClass().getMethod("endCall",null);
endCallMethod.setAccessible(true);
//调用endCall方法挂断电话
endCallMethod.invoke(object, null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
}