您的位置:首页 > 移动开发 > Android开发

Android之广播接收者获取短信并实现短信拦截

2016-06-15 22:05 459 查看
    系统在运行的过程中,要处理很多事件,比如本例的接收短信事件。一旦发生这些事件,系统会发送一个广播,为了接收到这个广播,知道系统做了什么事,就需要用到广播接收者。

下面通过一个小案例,来介绍广播接收者的使用:

1,定义一个广播接收者类,在这个类中具体实现获取广播中的内容:

<span style="font-size:18px;">package com.example.smslisten;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver{

//intent:广播发送时使用的intent
@Override
public void onReceive(Context context, Intent intent) {
//Bundle对象也是通过键值对的形式封装数据的
Bundle bundle = intent.getExtras();
//数组中的每个元素都是一条短信
Object[] objects = (Object[]) bundle.get("pdus");
//对数组中的每条短信进行遍历
for (Object object : objects) {
//通过pdu创建短信对象
SmsMessage sms = SmsMessage.createFromPdu((byte[]) object);
//获取发信人的号码
String address = sms.getOriginatingAddress();
//获取短信内容
String body = sms.getMessageBody();
System.out.println(address + ";" + body);
//通过匹配来拦截特定的号码
if ("183438".equals(address)) {
abortBroadcast();
}
}
}
}</span>

2,在清单文件中声明该广播接收者,需注意两点:

   ①广播接收者的name为"android.intent.category.LAUNCHER",因为出于安全考虑被谷歌屏蔽了,提示不出来,需自己正确敲出。

   ②要实现短信的拦截,需要在短信应用拿到短信之前把短信拦截掉,所以需要设置广播接收者的权限(priority)为最大。

<span style="font-size:18px;"><application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.smslisten.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>
<receiver android:name="com.example.smslisten.SmsReceiver">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application></span>

3,需要添加接收短信的权限:

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息