package com.pzq.test.zhuanpan4; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.telephony.SmsMessage; import android.text.TextUtils; import android.util.Log; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by asus on 2016/6/26. */ public class SMSUtils { private BroadcastReceiver smsReceiver, codeReceiver; private IntentFilter filter, mIntentFilter; private Handler handler; private String strContent; private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)"; private Activity mActivity; public static String MSMCode_CHANGE_BROADCAST = "com.pzq.test.SMSCode.CHANGE_BROADCAST"; public SMSUtils(Activity mActivity) { Log.d("mainpzqtest....", "getSMScode....444444444444444444444"); this.mActivity = mActivity; // getSMScode("555"); filter = new IntentFilter(); filter.addAction("android.provider.Telephony.SMS_RECEIVED"); filter.setPriority(Integer.MAX_VALUE); smsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { 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 (!TextUtils.isEmpty(from)) { String code = patternCode(message); if (!TextUtils.isEmpty(code)) { strContent = code; getSMScode(code); } } } } }; mActivity.registerReceiver(smsReceiver, filter); } /** * 匹配短信中间的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 void getSMScode(String code) { Intent intent = new Intent(); intent.putExtra("code", code); intent.setAction(MSMCode_CHANGE_BROADCAST); mActivity.sendBroadcast(intent); } /*** * 使用 加权限 <uses-permission android:name="android.permission.RECEIVE_SMS" /> * * registerReceiver(); u = new SMSUtils(MainActivity.this); * private void registerReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(SMSUtils.MSMCode_CHANGE_BROADCAST); registerReceiver(new SMSBroadcastReceiver(), intentFilter); } class SMSBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() == SMSUtils.MSMCode_CHANGE_BROADCAST) { Bundle bundle = intent.getExtras(); smScode = bundle.getString("code"); Log.d("mainpzqtest....", "mBroadcastReceiver...." + smScode); et.setText(smScode); } } }; * * */ }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。