Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 實戰:手機短信驗證碼獲取與注冊全流程解析

編輯:Android 開發實例

注冊各類 App 或網站賬號時,手機短信驗證碼幾乎是標配環節。曾經只覺得「手機收驗證碼」這件事挺新奇,卻沒深究背後是怎麼實現的。如今手上的項目正好需要通過手機號注冊、並發送驗證碼來完成驗證,於是索性把整套流程梳理清楚,順帶分享如何用正則表達式校驗手機號是否合法(覆蓋電信、移動、聯通號段)。

第一步:ApiClient 中封裝獲取驗證碼的方法

先在网络層封裝請求邏輯,拼接接口地址、發起請求並把返回的 JSON 解析為實體對象。

Java代碼
  1. /** 
  2.      * 說明:獲取驗證碼 
  3.      * 作者:丁國華 
  4.      * 時間:2015-8-27 下午5:47:36 
  5.      */  
  6.     public static String getValidateCode(AppContext appContext,  
  7.             Map<String, Object> map) throws AppException {  
  8.  
  9.         // 定義要訪問的接口和要強轉的實體  
  10.         String validateUrl = _MakeURL(URLs.VALIDATE_CODE_URL, map);  
  11.         ValidateCode validateCode = null;  
  12.  
  13.         try {  
  14.  
  15.             // 獲取服務器端Json數據  
  16.             String json = http_get(appContext, validateUrl);  
  17.  
  18.             // 解析為制定的實體對象  
  19.             validateCode = (ValidateCode) JSON.parseObject(json,  
  20.                     ValidateCode.class);  
  21.  
  22.         } catch (Exception e) {  
  23.         if (e instanceof AppException)  
  24.                 throw (AppException) e;  
  25.             throw AppException.network(e);  
  26.         }  
  27.  
  28.         // 返回驗證碼  
  29.         return validateCode.getCode();  
  30.     }  

第二步:AppContent 中編寫接口方法

這一步先判斷網絡是否可用,再調用上面的方法,異常時按情況拋出。

Java代碼
  1. /** 
  2.      * 說明:獲取服務器驗證碼(不需要緩存) 
  3.      * 作者:丁國華 
  4.      * @date 2015-8-28 上午9:07:14 
  5.      */  
  6.     public String getCode(Map<String, Object> map) throws AppException {  
  7.  
  8.         String validateCode = "" ;  
  9.  
  10.         // 如果網絡可連接且解析無誤返回正確的驗證碼,否則返回空字符串  
  11.         if (isNetworkConnected()) {  
  12.             try {  
  13.                 validateCode = ApiClient.getValidateCode(this, map);  
  14.             } catch (AppException e) {  
  15.                 if (validateCode == "") {  
  16.                     throw e;  
  17.                 }  
  18.             }  
  19.         }  
  20.         return validateCode;  
  21.     }  

第三步:用正則表達式校驗手機號

在 StringUtils 中封裝一個校驗方法,判斷輸入是否為合法的手機或固話號碼。

Java代碼
  1. /* 說明:移動:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188  
  2.       * 聯通:130、131、132、152、155、156、185、186 
  3.       * 電信:133、153、180、189  
  4.       * 總結起來就是第一位必定為1,第二位必定為3或5或8,其他位置的可以為0-9  
  5.       * 驗證號碼 手機號 固話均可  
  6.       * 作者:丁國華 
  7.       * 2015年9月20日 13:52:35  
  8.       */  
  9.     public static boolean isPhoneNumberValid(String phoneNumber) {  
  10.     boolean isValid = false;  
  11.  
  12.     String expression = "((^(13|15|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";  
  13.      CharSequence inputStr = phoneNumber;  
  14.  
  15.     Pattern pattern = Pattern.compile(expression);  
  16.  
  17.     Matcher matcher = pattern.matcher(inputStr);  
  18.  
  19.     if (matcher.matches() ) {  
  20.     isValid = true;  
  21.     }  
  22.  
  23.     return isValid;  
  24.  
  25.     }  

第四步:編寫注冊頁面的 XML 布局

注冊頁包含返回登錄按鈕、用戶名/手機號輸入框、驗證碼輸入框與「獲取驗證碼」按鈕、密碼輸入框、協議勾選,以及微信/微博/QQ 三種第三方登錄入口。

XML/HTML代碼
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.  
  7.     <LinearLayout style="@style/top_title_style" >  
  8.  
  9.         <Button  
  10.             android:id="@+id/register_back_login"  
  11.             android:layout_width="wrap_content"  
  12.             android:layout_height="wrap_content"  
  13.             android:layout_marginTop="5dp"  
  14.             android:background="@null"  
  15.             android:drawableLeft="@drawable/back"  
  16.             android:paddingLeft="5dp"  
  17.             android:text=" 登錄"  
  18.             android:textColor="#FFFFFF"  
  19.             android:textSize="18sp" />  
  20.  
  21.         <!-- 注冊的布局 -->  
  22.  
  23.         <TextView  
  24.             android:layout_width="wrap_content"  
  25.             android:layout_height="wrap_content"  
  26.             android:layout_margin="5dp"  
  27.             android:layout_marginTop="2dp"  
  28.             android:layout_weight="1"  
  29.             android:gravity="center"  
  30.             android:paddingLeft="4dp"  
  31.             android:text="注冊"  
  32.             android:textColor="#FFFFFF"  
  33.             android:textSize="20sp" />  
  34.  
  35.         <!-- 注冊的布局 -->  
  36.  
  37.         <TextView  
  38.             android:id="@+id/nickname_confirm"  
  39.             android:layout_width="wrap_content"  
  40.             android:layout_height="match_parent"  
  41.             android:layout_marginTop="2dp"  
  42.             android:gravity="center"  
  43.             android:paddingLeft="60dp"  
  44.             android:paddingRight="10dp"  
  45.             android:textColor="#FFFFFF"  
  46.             android:textSize="20sp" />  
  47.     </LinearLayout>  
  48.  
  49.     <RelativeLayout  
  50.         android:layout_width="fill_parent"  
  51.         android:layout_height="45dp"  
  52.         android:minHeight="50.0dip"  
  53.         android:paddingLeft="14.0dip"  
  54.         android:paddingRight="12.0dip" >  
  55.  
  56.         <ImageView  
  57.             android:layout_width="23.0dip"  
  58.             android:layout_height="23.0dip"  
  59.             android:layout_centerVertical="true"  
  60.             android:src="@drawable/user_picture" />  
  61.  
  62.         <EditText  
  63.             android:id="@+id/et_register_username_id"  
  64.             android:layout_width="wrap_content"  
  65.             android:layout_height="wrap_content"  
  66.             android:layout_marginLeft="20dp"  
  67.             android:background="@null"  
  68.             android:hint="用戶名/手機號"  
  69.             android:paddingLeft="15dip"  
  70.             android:paddingTop="8dp"  
  71.             android:textColorHint="#BEBEBE"  
  72.             android:textSize="20sp" />  
  73.     </RelativeLayout>  
  74.  
  75.     <View style="@style/PersonalLine" />  
  76.  
  77.     <RelativeLayout  
  78.         android:layout_width="fill_parent"  
  79.         android:layout_height="45dp"  
  80.         android:minHeight="50.0dip"  
  81.         android:paddingLeft="14.0dip"  
  82.         android:paddingRight="12.0dip" >  
  83.  
  84.         <ImageView  
  85.             android:layout_width="23.0dip"  
  86.             android:layout_height="23.0dip"  
  87.             android:layout_centerVertical="true"  
  88.             android:src="@drawable/phone_picture" />  
  89.  
  90.         <EditText  
  91.             android:id="@+id/et_register_code_id"  
  92.             android:layout_width="wrap_content"  
  93.             android:layout_height="wrap_content"  
  94.             android:layout_marginLeft="20dp"  
  95.             android:background="@null"  
  96.             android:hint="請輸入驗證碼"  
  97.             android:paddingLeft="15dip"  
  98.             android:paddingTop="8dp"  
  99.             android:textColorHint="#BEBEBE"  
  100.             android:textSize="20sp" />  
  101.  
  102.         <Button  
  103.             android:id="@+id/bt_getcode_id"  
  104.             android:layout_width="120dp"  
  105.             android:layout_height="35dp"  
  106.             android:layout_marginLeft="200dp"  
  107.             android:layout_marginTop="5dp"  
  108.             android:background="@drawable/shape1"  
  109.             android:text="獲取驗證碼"  
  110.             android:textColor="#FFFFFF"  
  111.             android:textSize="10sp" />  
  112.     </RelativeLayout>  
  113.  
  114.     <View style="@style/PersonalLine" />  
  115.  
  116.     <RelativeLayout  
  117.         android:layout_width="fill_parent"  
  118.         android:layout_height="45dp"  
  119.         android:minHeight="50.0dip"  
  120.         android:paddingLeft="14.0dip"  
  121.         android:paddingRight="12.0dip" >  
  122.  
  123.         <ImageView  
  124.             android:layout_width="23.0dip"  
  125.             android:layout_height="23.0dip"  
  126.             android:layout_centerVertical="true"  
  127.             android:src="@drawable/lock" />  
  128.  
  129.         <EditText  
  130.             android:id="@+id/et_register_password_id"  
  131.             android:layout_width="wrap_content"  
  132.             android:layout_height="wrap_content"  
  133.             android:layout_marginLeft="20dp"  
  134.             android:background="@null"  
  135.             android:hint="請輸入新密碼"  
  136.             android:paddingLeft="15dip"  
  137.             android:paddingTop="8dp"  
  138.             android:textColorHint="#BEBEBE"  
  139.             android:textSize="20sp" />  
  140.     </RelativeLayout>  
  141.  
  142.     <View style="@style/PersonalLine" />  
  143.  
  144.     <LinearLayout  
  145.         android:layout_width="fill_parent"  
  146.         android:layout_height="wrap_content"  
  147.         android:orientation="horizontal" >  
  148.  
  149.         <!-- 小對勾的布局 -->  
  150.  
  151.         <CheckBox  
  152.             android:layout_width="wrap_content"  
  153.             android:layout_height="wrap_content"  
  154.             android:layout_margin="10dp"  
  155.             android:layout_marginLeft="-10dp"  
  156.             android:scaleX="0.8"  
  157.             android:scaleY="0.8" />  
  158.  
  159.         <TextView  
  160.             android:layout_width="wrap_content"  
  161.             android:layout_height="wrap_content"  
  162.             android:layout_gravity="center_vertical"  
  163.             android:text="我同意"  
  164.             android:textSize="18sp" />  
  165.  
  166.         <TextView  
  167.             android:id="@+id/user_protocol"  
  168.             android:layout_width="200dp"  
  169.             android:layout_height="match_parent"  
  170.             android:layout_gravity="center_vertical"  
  171.             android:layout_marginLeft="5dp"  
  172.             android:gravity="center"  
  173.             android:text="用戶協議及隱私條款"  
  174.             android:textColor="#FE8B4A"  
  175.             android:textSize="18sp" />  
  176.     </LinearLayout>  
  177.  
  178.     <Button  
  179.         android:id="@+id/bt_register_id"  
  180.         android:layout_width="245dp"  
  181.         android:layout_height="45dp"  
  182.         android:layout_gravity="center_horizontal"  
  183.         android:layout_marginBottom="14dp"  
  184.         android:layout_marginLeft="15dp"  
  185.         android:layout_marginRight="15dp"  
  186.         android:layout_marginTop="5dp"  
  187.         android:background="@drawable/shape2"  
  188.         android:gravity="center"  
  189.         android:text="注  冊"  
  190.         android:textColor="#FFFFFF"  
  191.         android:textSize="15sp" />  
  192.  
  193.     <TextView  
  194.         android:layout_width="wrap_content"  
  195.         android:layout_height="wrap_content"  
  196.         android:layout_marginLeft="80dp"  
  197.         android:paddingTop="5dp"  
  198.         android:text="您也可以直接登錄"  
  199.         android:textColor="#BEBEBE"  
  200.         android:textSize="20sp" />  
  201.  
  202.     <LinearLayout  
  203.         android:layout_width="match_parent"  
  204.         android:layout_height="wrap_content"  
  205.         android:layout_marginTop="10dp"  
  206.         android:baselineAligned="false"  
  207.         android:gravity="center"  
  208.         android:orientation="horizontal" >  
  209.  
  210.         <LinearLayout  
  211.             android:layout_width="0dp"  
  212.             android:layout_height="wrap_content"  
  213.             android:layout_weight="1"  
  214.             android:gravity="center"  
  215.             android:orientation="vertical" >  
  216.  
  217.                 <Button  
  218.                     android:layout_width="60dp"  
  219.                     android:layout_height="60dp"  
  220.                 android:background="@drawable/weixin_login" />  
  221.  
  222.                 <TextView  
  223.                     android:layout_width="wrap_content"  
  224.                     android:layout_height="wrap_content"  
  225.                 android:text="微信登錄"  
  226.                 android:textColor="#BEBEBE"  
  227.                 android:textSize="20sp" />  
  228.            </LinearLayout>  
  229.  
  230.         <LinearLayout  
  231.             android:layout_width="0dp"  
  232.             android:layout_height="wrap_content"  
  233.             android:layout_weight="1"  
  234.             android:gravity="center"  
  235.             android:orientation="vertical" >  
  236.  
  237.                 <Button  
  238.                     android:layout_width="60dp"  
  239.                     android:layout_height="60dp"  
  240.                 android:background="@drawable/weibo_login" />  
  241.  
  242.                 <TextView  
  243.                     android:layout_width="wrap_content"  
  244.                     android:layout_height="wrap_content"  
  245.                 android:text="微博登錄"  
  246.                 android:textColor="#BEBEBE"  
  247.                 android:textSize="20sp" />  
  248.            </LinearLayout>  
  249.  
  250.         <LinearLayout  
  251.             android:layout_width="0dp"  
  252.             android:layout_height="wrap_content"  
  253.             android:layout_weight="1"  
  254.             android:gravity="center"  
  255.             android:orientation="vertical" >  
  256.  
  257.                 <Button  
  258.                     android:layout_width="60dp"  
  259.                     android:layout_height="60dp"  
  260.                 android:background="@drawable/qq_login" />  
  261.  
  262.                 <TextView  
  263.                     android:layout_width="wrap_content"  
  264.                     android:layout_height="wrap_content"  
  265.                 android:text="QQ登錄"  
  266.                 android:textColor="#BEBEBE"  
  267.                 android:textSize="20sp" />  
  268.            </LinearLayout>  
  269.     </LinearLayout>  
  270.  
  271. </LinearLayout>  

第五步:編寫 RegisterActivity 邏輯

核心邏輯都在這裡:點擊「獲取驗證碼」時先校驗手機號,再啟動倒計時線程更新按鈕文案,同時開子線程請求服務器;點擊「注冊」時校驗各項輸入並比對驗證碼,最後發起注冊請求。這裡用帶弱引用的靜態 Handler 來避免內存洩漏。

Java代碼
  1. package com.jczb.car.ui;  
  2.   
  3. import java.lang.ref.WeakReference;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.  
  7. import android.app.Activity;  
  8. import android.content.Intent;  
  9. import android.os.Bundle;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.TextView;  
  17. import android.widget.Toast;  
  18.  
  19. import com.jczb.car.AppContext;  
  20. import com.jczb.car.AppException;  
  21. import com.jczb.car.R;  
  22. import com.jczb.car.common.StringUtils;  
  23.  
  24. /** 
  25.  * 說明:注冊功能頁面 我們實現了取消線程的機制,從而保證它不會洩露 onDestroy()常常被用來在Activity推出前取消線程  
  26.  * 作者: 吳利昌 
  27.  * 時間: 2015-9-3上午9:19:15 
  28.  */  
  29. public class RegisterActivity extends Activity implements OnClickListener {  
  30.       
  31.        // 聲明用到的頁面控件  
  32.     private EditText etRegisterName;  
  33.     private EditText etCode;  
  34.     private EditText etPassword;  
  35.     private Button btCode;  
  36.     private Button btRegister;  
  37.     private TextView tvUserProtocol;  
  38.     private Button btRegisterLoginBack;  
  39.  
  40.     // 定義變量  
  41.     private String userName;  
  42.     private String passWord;  
  43.       
  44.     public boolean isChange = false;  
  45.     private boolean tag = true;  
  46.     private int i = 60;  
  47.     Thread thread = null;  
  48.       
  49.     /**客戶端輸入的驗證碼*/  
  50.     private String valicationCode;  
  51.       
  52.     /**服務器端獲取的驗證碼*/  
  53.     private static String serverValicationCode;  
  54.  
  55.     /** 注冊時所帶的參數 */  
  56.     private Map<String, Object> registerParams = new HashMap<String, Object>();  
  57.  
  58.     /** 獲取驗證碼時所帶的參數 */  
  59.     private Map<String, Object> codeParams = new HashMap<String, Object>();  
  60.  
  61.     /** 注冊是否成功 */  
  62.     private String regisgerStatus;  
  63.  
  64.     @Override  
  65.     protected void onCreate(Bundle savedInstanceState) {  
  66.         super.onCreate(savedInstanceState);  
  67.  
  68.         setContentView(R.layout.register);  
  69.         initView();       
  70.     }  
  71.       
  72.  
  73.     /** 
  74.      * 說明:初始化頁面控件和事件 
  75.      * 作者: 吳利昌 
  76.      * 時間: 2015-9-3 上午9:23:42 
  77.      */  
  78.     public void initView() {  
  79.         // 初始化控件  
  80.         etRegisterName = (EditText) findViewById(R.id.et_register_username_id);  
  81.         etCode = (EditText) findViewById(R.id.et_register_code_id);  
  82.         etPassword = (EditText) findViewById(R.id.et_register_password_id);  
  83.         btCode = (Button) findViewById(R.id.bt_getcode_id);  
  84.         btRegister = (Button) findViewById(R.id.bt_register_id);  
  85.         tvUserProtocol=(TextView)findViewById(R.id.user_protocol);  
  86.         btRegisterLoginBack=(Button)findViewById(R.id.register_back_login);  
  87.           
  88.         // 初始化監聽事件  
  89.         btCode.setOnClickListener(this);  
  90.         btRegister.setOnClickListener(this);  
  91.         tvUserProtocol.setOnClickListener(this);  
  92.         btRegisterLoginBack.setOnClickListener(this);  
  93.     }  
  94.       
  95.     private boolean isvalidate() {  
  96.         // TODO Auto-generated method stub  
  97.         // 獲取控件輸入的值  
  98.         String userName = etRegisterName.getText().toString().trim();  
  99.  
  100.           
  101.         if (StringUtils.isEmpty(userName)) {  
  102.             Toast.makeText(this, "手機號不能為空", Toast.LENGTH_SHORT).show();  
  103.             return false;  
  104.         }  
  105.         if (!StringUtils.isPhoneNumberValid(userName)) {  
  106.             Toast.makeText(this, "手機號有誤", Toast.LENGTH_SHORT).show();  
  107.             return false;  
  108.         }  
  109.         return true;  
  110.  
  111.     }  
  112.  
  113.     @Override  
  114.     public void onClick(View v) {  
  115.         switch (v.getId()) {  
  116.         case R.id.bt_getcode_id:  
  117.             if(!isvalidate())  
  118.                 break;  
  119.                   
  120.             btCode.setText("獲取驗證碼");  
  121.             btCode.setClickable(true);  
  122.             isChange = true;  
  123.             changeBtnGetCode();  
  124.             getValidateCode();  
  125.             break;  
  126.         case R.id.bt_register_id:  
  127.             register();  
  128.               
  129.             break;  
  130.         case R.id.user_protocol:  
  131.             Intent intentUserProtocol = new Intent(this,UserProtocolActivity.class);  
  132.             startActivity(intentUserProtocol);  
  133.             break;  
  134.         case R.id.register_back_login:  
  135.             this.finish();  
  136.             break;  
  137.               
  138.         default:  
  139.             break;  
  140.         }  
  141.  
  142.     }  
  143.       
  144.     private void changeBtnGetCode() {  
  145.         thread = new Thread() {  
  146.             @Override  
  147.             public void run() {  
  148.                 if (tag) {  
  149.                     while (i > 0) {  
  150.                         i--;  
  151.                         if (RegisterActivity.this == null) {  
  152.                             break;  
  153.                            
  154.                          
  155.                         RegisterActivity.this  
  156.                                 .runOnUiThread(new Runnable() {  
  157.                                     @Override  
  158.                                     public void run() {  
  159.                                        btCode.setText("獲取驗證碼("  
  160.                                                  + i + ")");  
  161.                                        btCode  
  162.                                                 .setClickable(false);  
  163.                                     }  
  164.                            });  
  165.                         try {  
  166.                             Thread.sleep(1000);  
  167.                         } catch (InterruptedException e) {  
  168.                         throw new RuntimeException(e);  
  169.                      }  
  170.                     };  
  171.                 tag = false;  
  172.                 }
  173.                i = 60;  
  174.                tag = true;  
  175.               if (RegisterActivity.this != null) {  
  176.                 RegisterActivity.this.runOnUiThread(new Runnable() {  
  177.                  @Override  
  178.                  public void run() {  
  179.                   btCode.setText("獲取驗證碼");  
  180.                   btCode.setClickable(true);  
  181.                  }  
  182.                 });  
  183.               }
  184.             };  
  185.         };  
  186.         thread.start();  
  187.     }  
  188.  
  189.     /** 
  190.      * 說明:獲取驗證碼 
  191.      *  
  192.      * 作者: 吳利昌 
  193.      * 時間: 2015-9-3 下午3:26:55 
  194.      */  
  195.     public boolean getValidateCode() {  
  196.           
  197.         String name = etRegisterName.getText().toString().trim();  
  198.         String code = etCode.getText().toString().trim();  
  199.         if (name.equals("")) {  
  200.             Toast.makeText(this, "請輸入用戶名或手機號!", Toast.LENGTH_SHORT).show();  
  201.             return false;  
  202.         }else {  
  203.             userName = name;  
  204.             valicationCode = code;  
  205.             Thread codeThread = new Thread(codeRunnable);  
  206.             codeThread.start();  
  207.         }
  208.         return true;  
  209.     }  
  210.  
  211.     /** 
  212.      * 說明:注冊 
  213.      *  
  214.      * 作者: 吳利昌 
  215.      * 時間: 2015-9-3 下午3:27:23 
  216.      */  
  217.     public void register() {  
  218.         // 1.首先判斷輸入的值是否有效  
  219.         // 2.然後判斷輸入的驗證碼是否有效(防止沒有點擊獲取驗證碼自己填的錯誤驗證碼)  
  220.         // 3.最後注冊  
  221.         if (isValid()) {  
  222.               
  223.             if (valicationCode.equals(serverValicationCode)) {  
  224.                 Thread thread = new Thread(sRunnable);  
  225.                 thread.start();  
  226.             }else {  
  227.                 Toast.makeText(this, "輸入的驗證碼不正確!", Toast.LENGTH_SHORT).show();  
  228.               
  229.             }  
  230.         }
  231.     }  
  232.       
  233.     //--------------------------------獲取驗證碼線程處理過程---開始-----------------------------  
  234.     /** 
  235.      * 自定義一個靜態的具有弱引用的Handler,解決內存洩漏的問題,本handler用來獲取驗證碼 
  236.      */  
  237.     private static class CodeHandler extends Handler {  
  238.         // 持有對本外部類的弱引用 
  239.         private final WeakReference<RegisterActivity> mActivity;  
  240.  
  241.         public CodeHandler(RegisterActivity activity) {  
  242.             mActivity = new WeakReference<RegisterActivity>(activity);  
  243.         }  
  244.  
  245.         @Override  
  246.         public void handleMessage(Message msg) {  
  247.               
  248.             // 獲取上下文對象 
  249.             RegisterActivity activity = mActivity.get();  
  250.             if (activity != null) {  
  251.                 switch (msg.what) {  
  252.                 case 1:  
  253.                 serverValicationCode = (String)msg.obj;  
  254.                     //activity.etCode.setText(serverValicationCode); 
  255.                     break;  
  256.                 case -1:  
  257.                   Toast.makeText(activity, "獲取驗證碼失敗!", Toast.LENGTH_SHORT).show();  
  258.                 break;  
  259.                 case 0:  
  260.                  Toast.makeText(activity, "哎呀,出錯啦..", Toast.LENGTH_SHORT).show();  
  261.                 break;  
  262.                default:  
  263.                break;  
  264.                } 
  265.             }
  266.         }  
  267.     }  
  268.       
  269.     /**實例化自定義的handler*/  
  270.     private final CodeHandler codeHandler = new CodeHandler(this);  
  271.       
  272.     private String serverCode=null;  
  273.       
  274.       
  275.     /**定義獲取驗證碼的子線程*/  
  276.     private Runnable codeRunnable = new Runnable() {  
  277.         @Override 
  278.         public void run() {  
  279.             Message msg = new Message();  
  280.             Map<String, Object> map = new HashMap<String, Object>();  
  281.             map.put("jbPhone", userName);  
  282.             // 獲取全局對象Application 
  283.             AppContext appContext = (AppContext) getApplication();  
  284.  
  285.             try {  
  286.                 // 獲取服務器數據 
  287.                 serverValicationCode = appContext.getCode(map);  
  288.  
  289.                 // 返回true則將消息的what值為1,為false則what為-1,異常為0 
  290.                 if (serverValicationCode.equals("")) {  
  291.                     msg.what = -1;  
  292.                }else {  
  293.                   msg.what = 1;  
  294.                   msg.obj = serverValicationCode;  
  295.                }  
  296.  
  297.             } catch (AppException e) {  
  298.                 msg.what = 0;  
  299.                 e.printStackTrace();  
  300.             }  
  301.             codeHandler.sendMessage(msg);  
  302.         }
  303.     };
  304.       
  305.     //--------------------------------獲取驗證碼線程處理過程----完成------------------------------ 
  306.  
  307.     //--------------------------------注冊線程處理過程--開始---------------------------------- 
  308.     /** 
  309.      * 自定義一個靜態的具有弱引用的Handler,解決內存洩漏的問題,注冊使用 
  310.      */ 
  311.     private static class MyHandler extends Handler { 
  312.         // 持有對本外部類的弱引用 
  313.         private final WeakReference<RegisterActivity> mActivity; 
  314.  
  315.         public MyHandler(RegisterActivity activity) { 
  316.             mActivity = new WeakReference<RegisterActivity>(activity); 
  317.         } 
  318.  
  319.         @Override 
  320.         public void handleMessage(Message msg) { 
  321.             
  322.             // 獲取上下文對象 
  323.             RegisterActivity activity = mActivity.get(); 
  324.             if (activity != null) { 
  325.                 switch (msg.what) { 
  326.                 case 1: 
  327.                 Toast.makeText(activity, "注冊成功!", Toast.LENGTH_SHORT).show(); 
  328.                 activity.finish(); 
  329.                 break; 
  330.                 case -1: 
  331.                 Toast.makeText(activity, "注冊失敗!", Toast.LENGTH_SHORT).show(); 
  332.                 break; 
  333.                 case -2: 
  334.                 Toast.makeText(activity, "該號已經注冊!", Toast.LENGTH_SHORT).show(); 
  335.                 break; 
  336.                 case 0: 
  337.                 Toast.makeText(activity, "哎呀,出錯啦..", Toast.LENGTH_SHORT).show(); 
  338.                 break; 
  339.                default: 
  340.                break; 
  341.                } 
  342.             }
  343.         }
  344.     }
  345.       
  346.     /**實例化自定義的handler*/ 
  347.     private final MyHandler mHandler = new MyHandler(this); 
  348.       
  349.     /**自定義子線程*/ 
  350.     private Runnable sRunnable = new Runnable() { 
  351.         @Override 
  352.         public void run() { 
  353.             Message msg = new Message(); 
  354.  
  355.             // 獲取全局對象Application 
  356.             AppContext appContext = (AppContext) getApplication(); 
  357.  
  358.             try { 
  359.                 // 獲取服務器數據 
  360.                 regisgerStatus = appContext.register(registerParams); 
  361.  
  362.                 // 返回true則將消息的what值為1,為false則what為-1,異常為0 
  363.                 if (regisgerStatus.equals("true")) { 
  364.                     msg.what = 1; 
  365.  
  366.                     msg.obj = regisgerStatus; 
  367.                 }else if(regisgerStatus.equals("1")){ 
  368.                     msg.what = -2; 
  369.  
  370.                }else if(regisgerStatus.equals("false")){ 
  371.                     msg.what = -1;} 
  372.  
  373.             } catch (AppException e) { 
  374.                 msg.what = 0; 
  375.                 e.printStackTrace(); 
  376.             } 
  377.             mHandler.sendMessage(msg); 
  378.         }
  379.     };
  380.  
  381.     //--------------------------------注冊線程處理過程---完成----------------------------------- 
  382.  
  383.     /** 
  384.      * 說明:注冊之前判斷數據是否為空 
  385.      *  
  386.      * @return 
  387.      * 作者: 吳利昌 
  388.      * 時間: 2015-9-3 下午3:29:04 
  389.      */ 
  390.     public boolean isValid() { 
  391.  
  392.         userName = etRegisterName.getText().toString().trim(); 
  393.         valicationCode = etCode.getText().toString().trim(); 
  394.         passWord = etPassword.getText().toString().trim(); 
  395.  
  396.           
  397.         if (userName.equals("")) { 
  398.             Toast.makeText(this, "用戶名不能為空!", Toast.LENGTH_SHORT).show(); 
  399.             return false; 
  400.         }
  401.  
  402.         if (valicationCode.equals("")) { 
  403.             Toast.makeText(this, "驗證碼不能為空!", Toast.LENGTH_SHORT).show(); 
  404.             return false; 
  405.         }
  406.  
  407.         if(!serverValicationCode.equals(valicationCode)) 
  408.         {
  409.             Toast.makeText(this, "驗證碼錯誤", Toast.LENGTH_SHORT).show(); 
  410.             return false; 
  411.         }
  412.  
  413.         if (passWord.equals("")) { 
  414.             Toast.makeText(this, "密碼不能為空!", Toast.LENGTH_SHORT).show(); 
  415.             return false; 
  416.         }else if (passWord.length() < 6) {
  417.             Toast.makeText(this, "密碼至少6位!", Toast.LENGTH_SHORT).show(); 
  418.             return false; 
  419.         }
  420.  
  421.         registerParams.put("username", userName); 
  422.         registerParams.put("psd", passWord); 
  423.  
  424.         return true; 
  425.     } 
  426. }

最後跑一遍看看效果。用一個號碼注冊,輸入手機號、點擊獲取驗證碼,倒計時會自動開啟,填好驗證碼與密碼後即可完成注冊。下面幾張圖展示了整個流程:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved