Automatic filling of SMS verification code in Android

Posted by p-co on Mon, 02 Dec 2019 15:53:31 +0100

Copyright notice: This is the original article of the blogger. It can't be reproduced without the permission of the blogger. https://blog.csdn.net/u010046908/article/details/47724807

Automatic filling of SMS verification code in Android

Because many applications now have SMS verification, it is troublesome for users to manually input the SMS verification code after receiving it, so I wrote this blog, hoping to help you.

Implementation steps:

1. Write a SmsBroadcastReceiver and register it in the AndroidMainifirst.xml file:

/** * Configure broadcast receiver: * < receiver Android: name = ". Smsbroadcastreceiver" >*  
<intent-filter android:priority="1000">Indicates: * set this broadcast receiver to the highest level */  
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>  
</intent-filter> 
</receiver> 


Class code:

public class SmsBroadcastReceiver extends BroadcastReceiver{

private  MessageListener mMessageListener;
    public SMSBroadcastReceiver() {
        super();
    }
@Override
public void onReceive(Context context, Intent intent) {
Object [] pdus= (Object[]) intent.getExtras().get("pdus");
        for(Object pdu:pdus){
           SmsMessage smsMessage=SmsMessage.createFromPdu((byte [])pdu);
           String sender=smsMessage.getDisplayOriginatingAddress();
           String content=smsMessage.getMessageBody();
           long date=smsMessage.getTimestampMillis();
           Date timeDate=new Date(date);
           SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           String time=simpleDateFormat.format(timeDate);
           System.out.println("Text messages from:"+sender+"Content of short message:"+content+"Short message time:"+time);
           mMessageListener.OnReceived(content);
           //If the message comes from 10690157263152, it will not be delivered down any more. Generally, this number can be used as the number of SMS platform.
           if("10690157263152".equals(sender)){
               System.out.println(" abort ");
               abortBroadcast();
           }
        }


}


// Callback interface
    public interface MessageListener {
        public void OnReceived(String message);
    }


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


Method used in Activity:


mSMSBroadcastReceiver=new SMSBroadcastReceiver();  
mSMSBroadcastReceiver.setOnReceivedMessageListener(new MessageListener() {  
public void OnReceived(String message) {  
mTextView.setText(message); }  
});

Conclusion: these three steps are very convenient, so that your application will never enter the verification code manually.

Topics: Android xml