Android realizes automatic SMS Verification code filling function _android

Source: Internet
Author: User

Android applications often involve registering the login function, and many of the registration or modify the password function often need to enter the SMS authentication code, usually, the user received the SMS need to minimize the application to see the text and then fill in the verification code, it is inevitable that the trouble, so it is necessary to automatically get issued a short message Convenient user's operation, the user experience is better.

Principle Explanation:

The main is real-time access to SMS messages. Involves the use of contentobserver classes. Using ContentProvider to monitor the change of the SMS database, implement OnChange method in the custom Contentobserver to monitor the SMS of specific mobile phone number, and then intercept the information in the filling position.
Contentobserver is the content listener, when we send a text message to the mobile phone, the phone will automatically call the Contentobserver in the specified method to notify the message has changed, then we read the contents of the message, the verification code extracted automatically filled into the input box, This completes the automatic filling function. The Contentobserver class mainly listens to the change of SMS content, which involves a design pattern commonly used by Android, i.e. observer mode.

Contentobserver EXPLANATION-Observer mode:

The Observer pattern (sometimes referred to as publish (publish)-Subscription (Subscribe), model-view, source-listener (Listener) or slave mode) is one of the software design patterns. In this mode, a target object manages all the observer objects that are dependent on it, and actively notifies it when its own state changes. This is usually done by calling the methods provided by the various observers. This pattern is often used to implement the event-handling system.
The Observer model (Observer) perfectly separated the observer from the observed object. The observer pattern defines clear boundaries between modules, increasing the maintainability and reusability of the application.
The observer design pattern defines a one-to-many dependency between objects so that when the state of an object changes, all objects that depend on it are notified and automatically refreshed.

The purpose of contentobserver--content watchers is to observe (capture) the changes in the database caused by a particular URI, and then do some corresponding processing, similar to a trigger (Trigger) in database technology, when the URI observed by contentobserver changes , it triggers it.
• The Observer (ie our application): Observer) registers itself with the observed object (Subject), and the observed object stores the observer in a container (Container).
• Being observed (i.e. the system's SMS application): the observed object has undergone some kind of change (as shown in the Somechange), from which all registered observers are notified and the changes are communicated to the observer.
• Revocation observation:
The Observer tells the observed to undo the observation, and the observer removes the observer from the container.

specifically to our project, that is, when the application is just starting to run, will be to our mobile phone system SMS application Register an observer, when the text message changes, the SMS application will notify the registered observer has changed, our observers receive such notification, will be based on the code to do the appropriate action, In order to achieve the relevant automatic completion of the verification code function. When we are done with the required functionality, we have to undo the observation, and the observer is removed from the container by the observed person. The observer is withdrawn and no longer receives notification of changes in the content of the message.

The steps to observe a specific URI are as follows:

1. To create our specific Contentobserver derived class, you must overload the parent class construction method, and you must overload the OnChange () method to handle the function implementation after the callback.
2. Use Context.getcontentresolover () to obtain the Contentresolove object, and then invoke the Registercontentobserver () method to register the content observer.
3. Since the life cycle of contentobserver is different from activity and Service, it is necessary to manually call Unregistercontentobserver () to cancel registration when it is not needed.

Activity_main.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
 xmlns:tools= "http:// Schemas.android.com/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:id=" @+id/et_validatecode "
  android:layout_width=" Wrap_ Content "
  android:layout_height=" wrap_content "
  android:layout_alignparenttop=" true "
  Android: Layout_centerhorizontal= "true"
  android:ems= "ten"/>
</RelativeLayout> 

Mainactivity.java

Package Smsdemo.com.smsdemo;
Import android.app.Activity;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;

Import Android.widget.EditText;
 /** * SMS Verification Code automatic filling function Implementation * 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) {super.oncreate (savedinstancestate);

  Setcontentview (R.layout.activity_main);

  Metvalidatecode = (edittext) Findviewbyid (R.id.et_validatecode);
  Mobserver = new Smsobserver (mainactivity.this, Mhandler);
  Uri uri = uri.parse ("content://sms");
 Register SMS Listening Getcontentresolver (). Registercontentobserver (URI, True, Mobserver);
  } @Override protected void OnPause () {super.onpause ();
 Getcontentresolver () Unregistercontentobserver (mobserver) for the cancellation of a registered SMS; Private Handler Mhandler =New Handler () {@Override public void Handlemessage (msg) {if (Msg.what = = Msg_received_code) {String
    Code = (String) msg.obj;
   Metvalidatecode.settext (code);

}
  }
 };

 }

Smsobserver.java

Package Smsdemo.com.smsdemo;
Import Android.content.Context;
Import Android.database.ContentObserver;
Import Android.database.Cursor;
Import Android.net.Uri;
Import Android.os.Handler;
Import Android.util.Log;
Import Java.util.regex.Matcher;

Import Java.util.regex.Pattern;
 /** * Created by Huangminzheng on 16/3/15.
 * * Observer object/public class Smsobserver extends contentobserver{the private context mcontext;

 Private Handler Mhandler;
  Public Smsobserver (context, Handler Handler) {super (Handler);
  Mcontext = context;
 Mhandler = handler;

  @Override public void OnChange (Boolean selfchange, Uri uri) {super.onchange (Selfchange, URI);
  LOG.D ("main", "SMS has changed!");
  LOG.D ("Main", uri.tostring ());
  When the message content changes, the first time the method is invoked, the message content is not written to the database, return if (uri.tostring (). Equals ("Content://sms/raw")) {return;
  Getvalidatecode ()//Get SMS Authentication Code}/** * Get SMS Authentication code/private void Getvalidatecode () {String code = ""; Uri Inboxuri = Uri.parse ("content://sms/iNbox "); Cursor C = mcontext.getcontentresolver (). query (Inboxuri, NULL, NULL, NULL, "date desc");/if (c!= null) {if (C.mov
    Etofirst ()) {String address = c.getstring (C.getcolumnindex (' address '));

    String BODY = c.getstring (C.getcolumnindex ("body"));
    13162364720 for the sender's mobile number if (!address.equals ("13162364720")) {return;

    LOG.D ("main", "Sender:" + address + "," + "SMS content is:" + body);
    Pattern pattern = Pattern.compile ("(\\d{6})");

    Matcher Matcher = Pattern.matcher (body);
     if (Matcher.find ()) {code = matcher.group (0);
     LOG.D ("main", "Verification Code is:" + code);
    Mhandler.obtainmessage (Mainactivity.msg_received_code, CODE). Sendtotarget ();
  } c.close ();
 }
 }
}

The URI of the text message has a few:

content://sms/inbox Inbox
content://sms/sent has been sent
Content://sms/draft Draft
Content://sms/outbox Outbox (information being sent)
content://sms/failed Send failed
content://sms/queued to send a list (for example, after the flight mode, the text message is in the outgoing column)

Of course, don't forget to add the right to read text messages:
<uses-permission android:name= "Android.permission.READ_SMS"/>

SOURCE download: Android SMS Verification code automatically fill

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.