Android applications often involve the registration and login function, and many functions of registering, logging in or modifying passwords often require input of SMS verification code. Usually, when users receive SMS, they need to minimize the application to view SMS and then fill in the verification code, which is inevitably troublesome. Therefore, it is necessary to automatically obtain the sent SMS verification code, which is convenient for users to operate and have a better user experience.
Principle explanation:
The main thing is to obtain SMS information in real time. Related to the use of ContentObserver class. Use ContentProvider to listen for changes in the SMS database, implement onChange method in a custom ContentObserver to listen for SMS messages on a specific mobile phone number, and then intercept information at the fill position that needs to be filled.
ContentObserver is the content listener. When we send a text message to the mobile phone, the mobile phone will automatically call the specified method in ContentObserver to notify the text message that there has been changes. Then we read the content in the text message, extract the verification code and automatically fill it in the input box, thus completing the automatic filling function. The ContentObserver class mainly monitors changes in SMS content, which involves a commonly used design pattern, namely the observer pattern, which is commonly used in Android.
ContentObserver explanation - Observer mode:
Observer mode (sometimes called publish-subscribe mode, model-view mode, source-listener mode or slave mode) is a type of software design mode. In this mode, a target object manages all observer objects that depend on it and actively issues notifications when its state changes. This is usually achieved by calling each observer's methods. This pattern is usually used to implement event processing systems.
Observer mode perfectly separates the observer from the observed object. Observer mode draws clear boundaries between modules, improving the maintainability and reusability of the application.
The observer design pattern defines a one-to-many dependency between objects so that when an object's state changes, all objects that depend on it are notified and automatically refreshed.
ContentObserver - Content Observer, the purpose is to observe (capture) the changes in the database caused by a specific Uri, and then do some corresponding processing. It is similar to the trigger (Trigger) in database technology. When the Uri observed by ContentObserver changes, it will be triggered.
•Observer (i.e. our application):Observer registers itself in the Subject, and the observed object stores the observer in a container.
• Observed (i.e., the system's SMS application):The object being observed has some change (as shown in SomeChange in the figure), and all registered observers are obtained from the container and notified the observer of the change.
•Revoke observation:The observer tells the observer to cancel the observation and removes the observer from the container.
Specifically in our project, that is, when the application starts to run, an observer will be registered with the SMS application of our mobile phone system. When the SMS changes, the SMS application will notify the registered observer that the change has occurred. When our observer receives such a notification, he will perform corresponding operations based on the code, thereby realizing the relevant function of automatically filling in the verification code. When we complete the required functions, we need to unregister, and remove the observer from the container by the observer. After the observer is revoked, he will no longer receive notifications of changes in the text message.
The steps to observe a specific Uri are as follows:
1. To create our specific ContentObserver derived class, the parent class constructor must be overloaded, and the onChange() method must be overloaded to handle the function implementation after the callback.
2. Use () to obtain the ContentResolove object, and then call the registerContentObserver() method to register the content observer.
3. Since the life cycle of ContentObserver is not synchronized with Activity and Service, when not required, you need to manually call unregisterContentObserver() to unregister.
activity_main.xml
<RelativeLayout xmlns:andro xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <EditText android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:ems="10" /> </RelativeLayout>
package ; import ; import ; import ; import ; import ; import ; /** * Implementation of automatic filling function of SMS verification code * * Created by huangminzheng on 16/3/15. */ public class MainActivity extends Activity { public static final int MSG_RECEIVED_CODE = 1; private EditText metValidateCode = null; private SmsObserver mObserver; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); metValidateCode = (EditText) findViewById(.et_validateCode); mObserver = new SmsObserver(, mHandler); Uri uri = ("content://sms"); //Register SMS monitoring getContentResolver().registerContentObserver(uri, true, mObserver); } @Override protected void onPause() { (); //Unregister the monitoring of SMS getContentResolver().unregisterContentObserver(mObserver); } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if ( == MSG_RECEIVED_CODE) { String code = (String) ; (code); } } }; }
package ; import ; import ; import ; import ; import ; import ; import ; import ; /** * Created by huangminzheng on 16/3/15. * * Observer object */ public class SmsObserver extends ContentObserver{ private Context mContext; private Handler mHandler; public SmsObserver(Context context, Handler handler) { super(handler); mContext = context; mHandler = handler; } @Override public void onChange(boolean selfChange, Uri uri) { (selfChange, uri); ("main", "SMS has changed!"); ("main", ()); // When the text message content changes, the text message content is not written to the database when the method is called for the first time, return if (().equals("content://sms/raw")) { return; } getValidateCode();//Get the SMS verification code } /** * Get the SMS verification code */ private void getValidateCode() { String code = ""; Uri inboxUri = ("content://sms/inbox"); Cursor c = ().query(inboxUri, null, null, null, "date desc");// if (c != null) { if (()) { String address = (("address")); String body = (("body")); //13162364720 is the sender's mobile number if (!("13162364720")) { return; } ("main", "Sendered by:" + address + " ," + "The text message content is:" + body); Pattern pattern = ("(\\d{6})"); Matcher matcher = (body); if (()) { code = (0); ("main", "The verification code is: " + code); (MainActivity.MSG_RECEIVED_CODE, code).sendToTarget(); } } (); } } }
There are several types of Uri for text messages:
content://sms/inbox Inbox
content://sms/sent Sent
content://sms/draft Draft
content://sms/outbox Outbox (the message being sent)
content://sms/failed Send failed
content://sms/queued List to send (for example, after the flight mode is turned on, the text message will be in the list to send)
Of course, don't forget to add permissions to read text messages:
<uses-permission android:name=".READ_SMS" />
Source code download:Automatically fill in Android SMS verification code
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.