android获取短信验证码并自动填写的实现一

时间:2022-11-03 20:11:58

现在的应用在注册登录或者修改密码中都用到了短信验证码,那在android中是如何实现获取短信验证码并自动填写的呢?


首先,需要要在manifest中注册接收和读取短信的权限:



<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"/>


实现一个广播SMSBroadcastReceiver来监听短信: 



package com.example.receive;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;


/**
* 短信监听
* @author
*
*/
public class SMSBroadcastReceiver extends BroadcastReceiver {

private static MessageListener mMessageListener;
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

public SMSBroadcastReceiver() {
super();
}

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
for(Object pdu:pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte [])pdu);
String sender = smsMessage.getDisplayOriginatingAddress();
//短信内容
String content = smsMessage.getDisplayMessageBody();
long date = smsMessage.getTimestampMillis();
Date tiemDate = new Date(date);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = simpleDateFormat.format(tiemDate);

//过滤不需要读取的短信的发送号码
if ("+8613450214963".equals(sender)) {
mMessageListener.onReceived(content);
abortBroadcast();
}
}
}

}

//回调接口
public interface MessageListener {
public void onReceived(String message);
}

public void setOnReceivedMessageListener(MessageListener messageListener) {
this.mMessageListener = messageListener;
}
}


在需要填写验证码的Activity中,生产SMSBroadcastReceiver的实例,实现onReceived的回调接口。为了节约系统资源,我们使用动态注册注销广播的方法。 


package com.example.smstest;

import com.example.receive.SMSBroadcastReceiver;

import android.os.Bundle;
import android.app.Activity;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.EditText;

public class MainActivity extends Activity {

private EditText edtPassword;
private SMSBroadcastReceiver mSMSBroadcastReceiver;

private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtPassword = (EditText) findViewById(R.id.password);
}

@Override
protected void onStart() {
super.onStart();
//生成广播处理
mSMSBroadcastReceiver = new SMSBroadcastReceiver();

//实例化过滤器并设置要过滤的广播
IntentFilter intentFilter = new IntentFilter(ACTION);
intentFilter.setPriority(Integer.MAX_VALUE);
//注册广播
this.registerReceiver(mSMSBroadcastReceiver, intentFilter);

mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
@Override
public void onReceived(String message) {

edtPassword.setText(message);

}
});
}

@Override
protected void onDestroy() {
super.onDestroy();
//注销短信监听广播
this.unregisterReceiver(mSMSBroadcastReceiver);
}
}

第二种方法是通过监听短信库的变化,使用 短信观察者
 
 
 
  1. ContentObserver c=new ContentObserver(han) {  
  2.                 @Override  
  3.                 public void onChange(boolean selfChange) {  
  4.                     // TODO Auto-generated method stub  
  5.                     super.onChange(selfChange);  
  6.                     han.sendEmptyMessage(0);  
  7.                 }  
  8.             };  
  9. getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, c);  
  10.   
  11.   
  12. Handler han = new Handler() {  
  13.         @SuppressWarnings("deprecation")  
  14.         public void handleMessage(android.os.Message msg) {  
  15.             String codestr = null;  
  16.             try {  
  17.                 codestr = Cus_UnitTools.getsmsyzm(Reg_ForgetPassword.this);  
  18.                 code.setText(codestr);  
  19.                 requestcode();  
  20.             } catch (Exception e) {  
  21.                 Log.e("yung""验证码提取失败:" + codestr);  
  22.             }  
  23.         };  
  24.     };    
  25.   
  26.     public static String getsmsyzm(Activity c) {  
  27.         Uri uri = Uri.parse("content://sms/inbox");  
  28.         String[] projection = new String[] { "address""person""body" };  
  29.         String selection = " address='" + JTPHONE + "' ";  
  30.         String[] selectionArgs = new String[] {};  
  31.         String sortOrder = "date desc";  
  32.         @SuppressWarnings("deprecation")  
  33.         Cursor cur = c.managedQuery(uri, projection, selection, selectionArgs,  
  34.                 sortOrder);  
  35.         if(cur!=null&&cur.getCount()>0){  
  36.             cur.moveToFirst();  
  37.             String body = cur.getString(cur.getColumnIndex("body")).replaceAll(  
  38.                     "\n"" ");  
  39.             cur.close();  
  40.             return getyzm(body, YZMLENGTH);  
  41.     }  
  42.         cur.close();  
  43.         return null;  
  44.     }  
  45.   
  46.   
  47.         /** 
  48.      * 从短信字符窜提取验证码 
  49.      * @param body 短信内容  
  50.          * @param YZMLENGTH  验证码的长度 一般6位或者4位 
  51.      * @return 接取出来的验证码 
  52.      */  
  53.     public static String getyzm(String body, int YZMLENGTH) {  
  54.         // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组合  
  55.         // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字  
  56.         // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现  
  57.         Pattern p = Pattern  
  58.                 .compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + YZMLENGTH + "})(?![a-zA-Z0-9])");  
  59.         Matcher m = p.matcher(body);  
  60.         if (m.find()) {  
  61.             System.out.println(m.group());  
  62.             return m.group(0);  
  63.         }  
  64.         return null;  
  65.     }  



请参考 http://blog.csdn.net/yung7086/article/details/26094987