Android广播接收短信的简单实现
说明: 接受短信广播,由Intent解析出短信内容明文, intent中的短信时已pud形式传出的,即byte[][]二位数组,
需要转化出明文SmsMessage.createFromPdu(pdus[i])
广播接收器:
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals(Intents.SMS_RECEIVED_ACTION)) {
SmsMessage[] msgs = getMessagesFromIntent(intent);
// to use this SmsMessage
String messageBody = "";
for (SmsMessage message : messages) {
messageBody += message.getMessageBody();
}
Log.i("MSG", messageBody);
}
}
}
/**
* Read the PDUs out of an {@link #SMS_RECEIVED_ACTION} or a* {@link #DATA_SMS_RECEIVED_ACTION} intent.
*
* @param intent
* the intent to read from
* @return an array of SmsMessages for the PDUs
*/
public static final SmsMessage[] getMessagesFromIntent(Intent intent) {
Object[] messages = (Object[]) intent
.getSerializableExtra("pdus");
if (messages == null) {
return null;
}
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++) {
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++) {
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]); //解析每一段pdu字节数组,返回解码明文
}
return msgs;
}
}
注意: manifest中声明权限:
<uses-permission android:name="android.permission.RECEIVE_SMS" /> //接收短信必须的权限
<uses-permission android:name="android.permission.READ_SMS"/> //读系统短信权限
<uses-permission android:name="android.permission.WRITE_SMS"/>//写系统短信权限
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。