首页 > 代码库 > Android自动获取短信验证码

Android自动获取短信验证码

  前言:android应用的自动化测试必然会涉及到注册登录功能,而许多的注册登录或修改密码功能常常需要输入短信验证码,因此有必要能够自动获得下发的短信验证码。

  主要就是实时获取短信信息。

  android上获取短信信息主要有BroadcastReceiver方式与数据库方式,要实时的话就BroadcastReceiver比较方便

public class SMSReceiver extends BroadcastReceiver{
   private String verifyCode="";
    public static final String TAG = "SMSReceiver";
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent){
       if (intent.getAction().equals(SMS_RECEIVED_ACTION)){
           SmsMessage[] messages = getMessagesFromIntent(intent);
           for (SmsMessage message : messages){
              Log.i(TAG, message.getOriginatingAddress() + " : " +
                  message.getDisplayOriginatingAddress() + " : " +
                  message.getDisplayMessageBody() + " : " +
                  message.getTimestampMillis());
              String smsContent=message.getDisplayMessageBody();
              Log.i(TAG, smsContent);            
              writeFile(smsContent);//将短信内容写入SD卡
           }
       }
    }

 public final SmsMessage[] getMessagesFromIntent(Intent intent){
        Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
        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]);
        }
        return msgs;
    }
  //将短信内容写到SD卡上的文件里,便于将文件pull到PC,这样可方便其它如WWW/WAP平台的自动化
    @SuppressLint("SdCardPath")
 public void writeFile(String str){
     String filePath="/mnt/sdcard/verifyCode.txt";    
     byte [] bytes = str.getBytes();
     try{
     File file=new File(filePath);
     file.createNewFile();
     FileOutputStream fos=new FileOutputStream(file);
     fos.write(bytes);
     fos.close();
     }catch(IOException e){
      e.printStackTrace();
     }     
    }