广播类
package com.examp.azuoyoutong.listner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
/**
* 短信-广播
* */
public class SMSBroadcastReceiver extends BroadcastReceiver {
private MessageListener mMessageListener;
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";
public SMSBroadcastReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
Object[] objs = (Object[]) intent.getExtras().get("pdus");
for (Object obj : objs) {
byte[] pdu = (byte[]) obj;
SmsMessage sms = SmsMessage.createFromPdu(pdu);
// 短信的内容
String message = sms.getMessageBody();
Log.d("logo", "message " + message);
// 短息的手机号。。+86开头?
String from = sms.getOriginatingAddress();
Log.d("logo", "from " + from);
//
// // // 过滤不需要读取的短信的发送号码
// // if ("+8613450214963".equals(sender)) {
// // mMessageListener.onReceived(content);
// // abortBroadcast();
// // }
if (!TextUtils.isEmpty(from)) {
String code = patternCode(message);
if (!TextUtils.isEmpty(code)) {
mMessageListener.onReceived(code);
}
}
}
}
}
/**
* 匹配短信中间的6个数字(验证码等)
*
* @param patternContent
* @return
*/
private String patternCode(String patternContent) {
if (TextUtils.isEmpty(patternContent)) {
return null;
}
Pattern p = Pattern.compile(patternCoder);
Matcher matcher = p.matcher(patternContent);
if (matcher.find()) {
return matcher.group();
}
return null;
}
// 回调接口
public interface MessageListener {
public void onReceived(String message);
}
public void setOnReceivedMessageListener(MessageListener messageListener) {
this.mMessageListener = messageListener;
}
}
activity中注册广播,并把验证码显示出来:
private void initBroastcast() {
// TODO Auto-generated method stub
IntentFilter intentFilter= new IntentFilter();
intentFilter.addAction(SMSBroadcastReceiver.SMS_RECEIVED_ACTION);
intentFilter.setPriority(Integer.MAX_VALUE);
mSMSBroadcastReceiver = new SMSBroadcastReceiver();
this.registerReceiver(mSMSBroadcastReceiver, intentFilter);
mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
@Override
public void onReceived(String message) {
reg_tel_code.setText(message);
// tt.showLongToast(RegActivity.this, message);
}
});
}
注意,注销广播;
@Override
protected void onDestroy() {
super.onDestroy();
//注销短信监听广播
this.unregisterReceiver(mSMSBroadcastReceiver);
}
另外,一定不要忘记xml配置中读取短信权限:
<!-- get短信-->
<uses-permission android:name="android.permission.RECEIVE_SMS" ></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" > </uses-permission>