歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android攔截短信並通知欄提醒

Android攔截短信並通知欄提醒

日期:2017/3/1 10:04:07   编辑:Linux編程

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

Copyright © Linux教程網 All Rights Reserved