核心类:SmsMessage、Smsmanager
特点:短信到达时,系统会进行广播,intent里携带短信内容。
接收短信
主要就是创建广播接收器接收短信广播
class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
// 提取短信消息
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
// 获取发送方号码
String address = messages[0].getOriginatingAddress();
String fullMessage = "";
for (SmsMessage message : messages) {
// 获取短信内容
fullMessage += message.getMessageBody();
}
sender.setText(address);
content.setText(fullMessage);
}
}
加入Action
receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(messageReceiver, receiveFilter);
加入接收短信的权限
< uses-permission android:name=”android.permission.RECEIVE_SMS” />
发送短信
使用SmsManager发送短信
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(to.getText().toString(), null,msgInput.getText().toString(), null, null);
加入发送短信的权限
< uses-permission android:name=”android.permission.SEND_SMS” />
拦截短信
因为短信就是广播,拦截短信就是注册高优先级广播监听器,并截断广播
receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
receiveFilter.setPriority(100);
abortBroadcast()