相关权限的声明
接收权限
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
发送权限
<uses-permission android:name="android.permission.SEND_SMS"/>
文本短信
发送
SmsManager.getDefault().sendTextMessage( strReceiveNumber, null, strMsgToSend, null, null);
拦截
注册广播监听
<application ...> ... <receiver android:name=".SMSReceiver"> <intent-filter android:priority="65535"> <action android:name="android.provider.Telephony.SMS_RECEIVED"></action> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </receiver> </application>
广播接收器
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 { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle bundle = intent.getExtras(); Object messages[] = (Object[]) bundle.get("pdus"); SmsMessage smsMessage[] = new SmsMessage[messages.length]; String msg = ""; for (int n = 0; n < messages.length; n++) { smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]); msg=smsMessage[n].getMessageBody(); if(msg.startsWith("paybest-sms:")){ msg=String.format("拦截到文本短信:\nfrom:%s\nmsg:%s\n",smsMessage[n].getOriginatingAddress(),msg); //SMSTest.setRMsg(msg); this.abortBroadcast(); } } } }
二进制短信
发送
SmsManager.getDefault().sendDataMessage( strReceiveNumber, null, SMSPort, strMsgToSend, null, null);
拦截
注册广播监听
<application ...> ... <receiver android:name=".DataSMSReceiver"> <intent-filter android:priority="65535"> <action android:name="android.intent.action.DATA_SMS_RECEIVED"/> <data android:scheme="sms" /> <data android:host="localhost" /> <data android:port="SMSPort"/> </intent-filter> </receiver> </application>
广播接收器
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; public class DataSMSReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub try{ Bundle bundle = intent.getExtras(); Object messages[] = (Object[]) bundle.get("pdus"); SmsMessage smsMessage[] = new SmsMessage[messages.length]; String msg = ""; for (int n = 0; n < messages.length; n++) { smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]); byte b[]=smsMessage[n].getUserData(); for (int i = 0; i < b.length; i++) { msg+=String.format("%02X", b[i]); } msg=String.format("拦截到二进制短信:\nfrom:%s\nmsg:%s\n",smsMessage[n].getOriginatingAddress(),msg); //SMSTest.setRMsg(msg); this.abortBroadcast(); } }catch(Exception e) { //SMSTest.setRMsg(e.toString()); } }