Android拦截短信并通知栏提醒

SMSReceiver.java

public class SMSReceiver extends BroadcastReceiver{
	
	public static int TEST_ID = 1;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("SMSReceiver, isOrderdeBroadcast()="+isOrderedBroadcast());
		
		Bundle bundle = intent.getExtras();
		Object messages[] = (Object[]) bundle.get("pdus");
		if (messages!=null && messages.length>0) {
			SmsMessage smsMessage[] = new SmsMessage[messages.length];
			for (int n = 0; n < smsMessage.length; n++) {
				smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
			}
			for (SmsMessage message : smsMessage) {
				String content = message.getMessageBody();//得到短信内容
				String sender = message.getOriginatingAddress();//得到发件人号码
				if (sender.equals("10086") && content.contains("000")) {
					this.abortBroadcast();
					System.out.println(sender+"已拦截,信息内容为:"+ content);
					
					NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
					Notification mNotification = new Notification(R.drawable.ic_launcher, "new message", System.currentTimeMillis());
					mNotification.flags = mNotification.FLAG_AUTO_CANCEL | mNotification.FALG_NO_CLEAR;//设置图标自动清除或不可清除	
					//绑定itent,点击图标时能够进入某activity
					Intent mIntent = new Intent(context,SMSIntercept.class);
					PendingIntent mPendingIntent = PendingIntent.getActivity(context, 0, mIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
					CharSequence contentTitle = "提醒标题";
					CharSequence contentText = "你有新消息提醒。";
					mNotification.setLatestEventInfo(context, contentTitle, contentText, mPendingIntent);
					//发送通知
					mNotificationManager.notify(TEST_ID, mNotification);//TEST_ID在清除通知栏图标的时候要用到。
				}
			}
		}
	}
}

清除通知栏图标:

NotificationManager mNotificationManager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
        mNotificationManager.cancel(SMSReceiver.TEST_ID);

从上面可以看出,他是一个OrderedBroadcast,根据这一点我们可以对短信机制进行拦截。

AndroidManifest.xml文件中配置receiver:

注意其优先级是10000,设置为最大,因为OrderedBroadcast是根据优先级来传递消息的,优先级越高越先获取到消息。

<receiver android:name = ".SMSReceiver">
            <intent-filter android:priority="10000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </receiver>

此外还要在AndroidManifest.xml文件中加入短信权限:

<uses-permission  android:name="android.permission.RECEIVE_SMS"/>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值