需要接受信息和播出电话的权限
广播接受者需要在配置清单里面注册,并且可以设置优先级和接收者关心的事件
广播拦截下来之后可以进行传递的信息的修改或者直接终止掉广播,终止了之后就相当于没有这个事情发生
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.smsreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.itheima.smsreceiver.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 优先级从-1000到1000 1000是优先级最高的-->
<receiver android:name="com.itheima.smsreceiver.SmsReceiver">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
<!-- 配置广播接受者 -->
<receiver android:name="com.itheima.smsreceiver.OutCallReceiver">
<intent-filter android:priority="1000">
<!-- 配置广播接收者关心的事件是外拨电话 -->
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
</application>
</manifest>
有短信来了就触发关注短信事件的广播接受者
package com.itheima.smsreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("短信到来了。 。。。");
//获取一组短信 有多条,所以是数组类型
Object[] objs = (Object[]) intent.getExtras().get("pdus");//pdus短信的工业描述标准
for (Object obj : objs) {
// 得到短信对象 createFromPdu可以把pdus类型转化为短信对象
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) obj);
//得到消息的内容
String body = smsMessage.getMessageBody();
//得到消息的发件人
String sender = smsMessage.getOriginatingAddress();
System.out.println("body:" + body);
System.out.println("sender:" + sender);
// 终止掉当前的广播。。也就是把短信拦截掉。 如果有服务器就把短信发送到你的服务器也可以,没有服务器的话就转发也行
//对应的配置文件要设置为优先级最高,否则就没用
if ("5556".equals(sender)) {
abortBroadcast();
}
}
}
}
当拨打出电话时就触发对播出电话事件关注的广播接受者
package com.itheima.smsreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class OutCallReceiver extends BroadcastReceiver {
//当接收到消息对应的方法
@Override
public void onReceive(Context context, Intent intent) {
String number = getResultData();
if("5556".equals(number)){
setResultData(null);
}
}
}