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

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

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

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"/>

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值