Android拦截短信并通知栏提醒

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

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/774dd14cad0c144a07cb176625ddf92a.html