Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > android获取验证码

Android如何通过手机自动获取短信验证码

投稿:lijiao

注册帐号时,经常需要手机获取验证码,Android如何通过手机自动获取短信验证码,下面看看小编给大家分享的一段代码,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Android实现手机自动获取短信验证码功能,供大家参考,具体内容如下

1、短信监听广播

2、读取短信内容

3、截取短信内容【可以 reg截取】

4、填写至相应控件

PS:DevStore测试没有获取到验证码

源码片段

public class MainActivity extends Activity { 
 private BroadcastReceiver smsReceiver; 
 private IntentFilter filter2; 
 private Handler handler; 
 private EditText et; 
 private String strContent; 
 private String patternCoder = "(?<!--\\d)\\d{6}(?!\\d)"; 
 
 @Override 
 protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main); 
  et = (EditText) findViewById(R.id.et); 
  handler = new Handler() { 
   public void handleMessage(android.os.Message msg) { 
    et.setText(strContent); 
   }; 
  }; 
  filter2 = new IntentFilter(); 
  filter2.addAction("android.provider.Telephony.SMS_RECEIVED"); 
  filter2.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); 
     Time time = new Time(); 
     time.set(sms.getTimestampMillis()); 
     String time2 = time.format3339(true); 
     Log.d("logo", from + " " + message + " " + time2); 
     strContent = from + " " + message; 
     handler.sendEmptyMessage(1); 
     if (!TextUtils.isEmpty(from)) { 
      String code = patternCode(message); 
      if (!TextUtils.isEmpty(code)) { 
       strContent = code; 
       handler.sendEmptyMessage(1); 
      } 
     } 
    } 
   } 
  }; 
  registerReceiver(smsReceiver, filter2); 
 } 
 
 @Override 
 protected void onDestroy() { 
  super.onDestroy(); 
  unregisterReceiver(smsReceiver); 
 } 
 
 /** 
  * 匹配短信中间的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; 
 } 
}</pre--> 

文章末尾为大家在分享两个专题,供大家参考:

《PHP验证码大全》

《ASP.NET验证码大全》

以上就是Android通过手机自动获取短信验证码的详细代码,希望对大家实现手机自动获取短信验证码有所帮助。

您可能感兴趣的文章:
阅读全文