The automated testing of Android application will inevitably involve registration login function, and many registration login or change password function often need to enter SMS verification code, so it is necessary to automatically obtain the Issued SMS Verification code.
The main is real-time access to SMS information.
On Android to get text messages mainly have Broadcastreceiver way and database way, to real-time words on broadcastreceiver more convenient
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);//write SMS content to SD card
}
}
}
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;
}
Write the text to the SD card file, easy to pull the file to the PC, so as to facilitate other automation such as the Www/wap platform
@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 ();
}
}