android自動獲取短信驗證碼

前言:android應用的自動化測試必然會涉及到註冊登陸功能,而許多的註冊登陸或修改密碼功能經常須要輸入短信驗證碼,所以有必要可以自動得到下發的短信驗證碼。
主要就是實時獲取短信信息。
android上獲取短信信息主要有BroadcastReceiver方式與數據庫方式,要實時的話就BroadcastReceiver比較方便java

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();
}
} android

如此當有短信收到時就能夠將短信內容寫到SD卡中的文件裏
在另外一個java類中寫個讀取文件內容的方法,並在寫測試用例過程當中,將獲得的String按驗證碼的具體位置截取便可。數據庫

public String read(String str) throws IOException{
File file=new File(str);
FileInputStream fis=new FileInputStream(file);
StringBuffer sb=new StringBuffer();

BufferedInputStream bis=new BufferedInputStream(fis);
BufferedReader read = new BufferedReader (new InputStreamReader(bis));
int c=0;
while ((c=read.read())!=-1) {
sb.append((char) c);
}
read.close();
bis.close();
fis.close();
Log.i(TAG, sb.toString());
String verify=sb.toString();
return verify;
}app

最後須要在manifest中增長申明,且註冊權限
<receiver android:name="com.cplatform.surfdesktop.test.util.SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"/>
測試過程當中須要用到短信驗證碼時就能夠實時獲取了ide

相關文章
相關標籤/搜索