The method of integrating mob SMS authentication code in ANDROID development project _android

Source: Internet
Author: User
Tags gettext md5 md5 encryption throwable

I. Preface

Now the app basically needs to use the SMS function, when you register or have a message when you need to send a text message to the user, but for personal developers, to buy a third party SMS service is a bit extravagant, very good is mob for us to provide a free text message authentication Code service function, I am not playing ads, I really think this service is very good. Then the following simple talk about how in their own project integrated mob SMS function, in fact, the whole process is not complicated, just a person feel mob official document a little messy, official demo is a little bit complicated, at the same time some details of the place is easy to ignore, also can cause some problems.
PS: Too like the logo of mob.

Two. Implementation process

This article only deals with Android, and if it's iOS, look at it for yourself, and hopefully this article will help you as well, while the IDE is Android Studio.

1.key Application

Application Address:http://www.mob.com, select the SMS Authentication Code SDK in the Product center, and then complete the corresponding registration and application work;
Go to your Back center and you'll see your app key and app Secret:

The overall trend bar shows us some of the use of SMS services. Not online registration, we can use 20/day for free, if the demand is larger, we can in their own project integrated mob SMS, and then online registration, should be able to get more free text message number, no attempt.

2. Download SDK

Select SMS for Android in the SDK download section and select the corresponding IDE's SDK (this IDE is as)


After downloading it is probably like this:

3. Integration process

The application to the key and secret is integrated into their own projects. Mob mainly provides two kinds of interface methods: 1 using the official ui;2) using a GUI-free interface.

3.1. Configure the SDK

This is already the old rules for using Third-party interfaces. The official website document I do not post, really looked uncomfortable, here only pastes own.

The first is to add a jar bundle and an. aar file under the Libs of the project.

Then add the dependencies in the Build.gradle

Add appropriate permissions to the Androidmanifest and register the corresponding activity

 <!--mob SMS required permissions--> <uses-permission android:name= "Android.permission.READ_PHONE_STATE"/> <uses-perm Ission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/> <uses-permission android:name=" android.permission.ACCESS_WIFI_ State "/> <uses-permission android:name=" Android.permission.INTERNET "/> <uses-permission android:name=" Android.permission.RECEIVE_SMS "/> <uses-permission android:name= Android.permission.GET_TASKS"/> <
 Uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/> <!--registered activity in application--> <!--Mob SMS (if the use of no GUI, this activity should be able to do not need, they have not tried, the first registration in this bar)--> <activity android:name= " Com.mob.tools.MobUIShell "android:configchanges=" Keyboardhidden|orientation|screensize "Android:theme=" @android: Style/theme.translucent.notitlebar "android:windowsoftinputmode=" statehidden|adjustresize "> &LT;/activity>

 

3.2. Call the interface to send SMS

As mentioned earlier, the mob provides both GUI and no GUI, either way, it is necessary to initialize the SMSSDK first, and then invoke the interface.

Initialize: SMSSDK.INITSDK (Loginactivity.this, "app Key", "app Secret");

1 GUI, that is, using the interface provided by mob

The method is as follows:

 Registertext.setonclicklistener (New View.onclicklistener () {
  @Override public
  void OnClick (View v) {
  // First Initialize SMSSDK
  smssdk.initsdk (loginactivity.this, "app Key", "app Secret");
  Registerpage registerpage = new Registerpage ();
  callback function
  Registerpage.setregistercallback (new EventHandler ()
  {public
   void afterevent (int event, int result, Object data)
   {
   //Parse Results
   if (consequence = = Smssdk. Result_complete)
   {
   //Submit Verification Code Success
   if (event = = Smssdk. Event_submit_verification_code)
   {
   }
   ///Commit verification code succeeded, at which time it was verified to have succeeded
   else if (event = = Smssdk. Event_get_verification_code)
   {}}}}
  );
  Registerpage.show (loginactivity.this);
  }
 );

2) No GUI

This situation is typically the use of their own activity interface, and then integrated SMS features, such as a simple registration.

I only provide some key code, the rest is not available, too, too much, looks too miscellaneous public class Activitymessageregister extends activity {private static final int code_i   NG = 1;  Sent, countdown private static final int code_repeat = 2;  Resend private static final int smsddk_handler = 3; SMS callback private int time = 60;//countdown 60s @Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (s)
 Avedinstancestate);
 Setcontentview (R.layout.activity_message_register); Initview ()//Interface Initialization INITSDK ()//SMS Initialization}//initialization interface void Initview () {userphonetext = (edittext) Findviewbyid (r.id.user_ph
 One_input);
 Userpasswordtext = (edittext) Findviewbyid (r.id.user_password_input);
 Usernametext = (edittext) Findviewbyid (r.id.user_name_input);
 Registerbutton = (Button) Findviewbyid (R.id.register_button);
 Registerbutton.setonclicklistener (New Onclicklistener ());
 LoginView = (TextView) Findviewbyid (R.id.login_view);
 Getcodebutton = (Button) Findviewbyid (R.id.get_code_button);
 Getcodebutton.setonclicklistener (New Onclicklistener ()); CodEText = (edittext) Findviewbyid (R.id.code_view);
 ...//}//Initialize smssdk private void Initsdk () {SMSSDK.INITSDK (this, "app Key", "app Secret"); EventHandler = new EventHandler () {@Override public void afterevent (int event, int result, Object data) {Message M
  SG = new Message ();
  Msg.arg1 = event;
  MSG.ARG2 = result;
  Msg.obj = data;
  Msg.what = Smsddk_handler;
  Handler.sendmessage (msg);
 }
 };
 Register Callback Listener Interface Smssdk.registereventhandler (EventHandler); }//Listener function Private class Onclicklistener implements View.onclicklistener {@Override public void OnClick (View v) {US
  Erphone = Userphonetext.gettext (). toString (); Switch (V.getid ()) {case r.id.get_code_button://gets the authentication code new Alertdialog.builder (Activitymessageregister.this). Set Title ("Send SMS"). Setmessage ("We will send the verification code to the following number: \ n" + "+86:" +userphone). Setpositivebutton ("OK", new DIALOGINTERFACE.ONCLI Cklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {SMSSDK. Getverificationcode ("Userphone",);
     Getcodebutton.setclickable (FALSE);
      New Thread (New Runnable () {@Override public void run () {for int i = > 0; i--)
      {handler.sendemptymessage (code_ing);
      if (I <= 0) {break;
      try {thread.sleep (1000);
      catch (Interruptedexception e) {e.printstacktrace ();
     } handler.sendemptymessage (Code_repeat);
    }). Start ();
   ). Create (). Show ();

  Break Case r.id.register_button://Registered Smssdk.submitverificationcode ("", Userphone, Codetext.gettext (). toString ());//
  Verifying the verification code-> the callback function break;
  Default:break; }} Handler Handler = new Handler () {public void Handlemessage (msg) {switch (msg.what) {case CODE
   _ING://has been sent, the countdown Getcodebutton.settext ("Resend (" +--time+ "s)");
  Break
   Case code_repeat://Resend Getcodebutton.settext ("Get Authentication Code"); Getcodebutton.setcLickable (TRUE);
  Break
   Case Smsddk_handler:int event = MSG.ARG1;
   int result = MSG.ARG2;
   Object data = Msg.obj; The callback completes if (result = = Smssdk. Result_complete) {//Validation code Verification Success if (event = = Smssdk.
    Event_submit_verification_code) {Toast.maketext (Activitymessageregister.this, "Validation successful", Toast.length_long). Show ();
    if (check ())//other legitimacy of the detection {Usermodel user = new Usermodel ();  User.setuserid (Myuuid.getuuid ());
    ID User.setuserphone (userphone); User.setuserpassword (MD5.MD5 (UserPassword));   MD5 encryption User.setusergender (gender);
    Gender User.setusername (UserName);   User.setuserbirthday ("19920401");
    Temporarily empty//user.setuseridcard (Useridcard);    User.setuserimage ("");
    temporarily empty//register-> server Usercontroller.userregister (user, Handler); Verify code else if (event = = Smssdk.
   Event_get_verification_code) {Toast.maketext (Getapplicationcontext (), "Verify code has been sent", Toast.length_short). Show (); } else {((throwable) data). Printstacktrace (); } if (RESULT==SMSSDK.
    Result_error) {try {throwable throwable = (throwable) data;
    Throwable.printstacktrace ();
    Jsonobject object = new Jsonobject (Throwable.getmessage ()); String des = object.optstring ("detail");/error description int status = Object.optint ("status");/error code if (Status > 0 & &!
    Textutils.isempty (des)) {Toast.maketext (Getapplicationcontext (), DES, Toast.length_short). Show ();
    Return
  } catch (Exception e) {//do something}} break;
   Case R.id.register_status:string Result_code = Msg.getdata (). getString ("result"). ToString ();
   if ("1". Equals (Result_code)) {Toast.maketext (Activitymessageregister.this, "registered successfully", Toast.length_long). Show ();
   Intent Intent = new Intent (activitymessageregister.this,loginactivity.class);
   Intent.putextra ("Userphone", Userphone);
   ActivityMessageRegister.this.setResult (Resule_code, intent);
   StartActivity (Intent); FinisH ();
   }else {toast.maketext (activitymessageregister.this, "registration failed", Toast.length_long). Show ();
  } break;
   Case r.id.check_phone_exist://cell phone number exists String result_code_2 = Msg.getdata (). getString ("result"). ToString ();
   if ("1". Equals (result_code_2)) {Errphonetext.settext ("mobile number has been registered, please replace it with another number");
   Resultmap.put ("Phone", false);
   else {Errphonetext.settext ("");
   Resultmap.put ("Phone", true);
  } break;
}
 }
 };

 }

OK, basically it's done.

Three. The question

There may be several issues in integration:

1. Unable to receive SMS authentication code

Mob the default is to turn on intelligent authentication, also means that if a number through a verification code verification, then again after the text message verification, will be intelligent validation through, and at this time is not receiving the verification code, because the mob will not be issued a verification code. This has a certain impact on our testing, sometimes we can not receive the verification code, the reason is here. Into the background, the intelligent verification function will be closed. Background Center-> SMS Setup-> Intelligent Verification
Here to write a picture description

2. After the success of the SMS verification, did not execute the corresponding code, but returned to a certain interface

It is also possible that the reason for intelligent authentication.

EventHandler = new EventHandler () {
  @Override public
  void afterevent (int event, int result, Object data) 
  {
   if (Result = = Smssdk. Result_complete)
  {
   if (event = = Smssdk. Event_submit_verification_code)
   {
   //The official documentation says that if intelligent authentication requires only the data to be judged here, if
   ((Boolean) data)//is an intelligent authentication
   {
    //If the IF statement is added, then if intelligent authentication is turned off, then the data is coerced to Boolean and true, so the corresponding code is not executed, so if you don't need intelligent validation when you integrate, The best way is to not take care of the function.
   }
   else
   {
    //non-
   intelligent
   }
  }}}

So, the most appropriate way is to completely discard the intelligent authentication function.

This is the entire content of this article, I hope to learn more about Android software programming help.

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.