編輯:Android 開發實例
注冊賬號時「填手機號 → 收驗證碼 → 提交注冊」這條路徑,幾乎每個 App 都有。本文以一個注冊頁為例,把網絡請求分層、驗證碼倒計時、Handler 線程通信、弱引用防洩露以及手機號正則校驗一次講透。
代碼按三層拆分:ApiClient 負責拼 URL 與發請求並解析 JSON;AppContext 作為全局對象對外暴露業務方法;RegisterActivity 只處理界面與交互。這樣分的好處是網絡細節不外泄,界面層保持乾淨。
/**
* 說明:獲取驗證碼
*/
public static String getValidateCode(AppContext appContext, Map<String, Object> map)
throws AppException {
// 定義要訪問的接口和要強轉的實體
String validateUrl = _MakeURL(URLs.VALIDATE_CODE_URL, map);
ValidateCode validateCode = null;
try {
String json = http_get(appContext, validateUrl); // 拿到服務端 JSON
validateCode = (ValidateCode) JSON.parseObject(json, ValidateCode.class);
} catch (Exception e) {
if (e instanceof AppException) throw (AppException) e;
throw AppException.network(e);
}
return validateCode.getCode();
}
在這層統一判斷網絡狀態,讓上層不必關心離線情況:
/**
* 說明:獲取服務器驗證碼(不需要緩存)
*/
public String getCode(Map<String, Object> map) throws AppException {
String validateCode = "";
// 有網絡且解析無誤返回真實驗證碼,否則返回空字符串
if (isNetworkConnected()) {
try {
validateCode = ApiClient.getValidateCode(this, map);
} catch (AppException e) {
if (validateCode == "") {
throw e;
}
}
}
return validateCode;
}
把校驗邏輯抽到 StringUtils,避免在界面層散落判斷:
/* 號段參考(寫於 2015 年):
* 移動:134-139、150、151、157(TD)、158、159、187、188
* 聯通:130、131、132、152、155、156、185、186
* 電信:133、153、180、189
* 規律:第一位必為 1,第二位為 3/5/8,其餘位為 0-9
* 此方法同時兼容手機與固話格式
*/
public static boolean isPhoneNumberValid(String phoneNumber) {
boolean isValid = false;
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})$))";
CharSequence inputStr = phoneNumber;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
這裡要提醒一句:號段是會隨時間變化的,運營商不斷放出新號段(如 166、199、198 等),寫死的正則遲早會誤判。更穩健的寫法是只校驗「1 開頭 + 第二位 3~9 + 共 11 位數字」,即 ^1[3-9]\\d{9}$,把具體號段的精確判斷交給服務端去做。
結構自上而下依次為:頂部返回與標題、用戶名輸入、驗證碼輸入(帶「獲取驗證碼」按鈕)、密碼輸入、協議勾選、注冊按鈕、第三方登錄入口。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout>
<Button
android:id="@+id/register_back_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="@null"
android:drawableLeft="@drawable/back"
android:paddingLeft="5dp"
android:text=" 登錄"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:gravity="center"
android:paddingLeft="4dp"
android:text="注冊"
android:textColor="#FFFFFF"
android:textSize="20sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="45dp"
android:minHeight="50.0dip"
android:paddingLeft="14.0dip"
android:paddingRight="12.0dip" >
<ImageView
android:layout_width="23.0dip"
android:layout_height="23.0dip"
android:layout_centerVertical="true"
android:src="@drawable/user_picture" />
<EditText
android:id="@+id/et_register_username_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="@null"
android:hint="用戶名/手機號"
android:paddingLeft="15dip"
android:paddingTop="8dp"
android:textColorHint="#BEBEBE"
android:textSize="20sp" />
</RelativeLayout>
<View />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="45dp"
android:minHeight="50.0dip"
android:paddingLeft="14.0dip"
android:paddingRight="12.0dip" >
<ImageView
android:layout_width="23.0dip"
android:layout_height="23.0dip"
android:layout_centerVertical="true"
android:src="@drawable/phone_picture" />
<EditText
android:id="@+id/et_register_code_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="@null"
android:hint="請輸入驗證碼"
android:paddingLeft="15dip"
android:paddingTop="8dp"
android:textColorHint="#BEBEBE"
android:textSize="20sp" />
<Button
android:id="@+id/bt_getcode_id"
android:layout_width="120dp"
android:layout_height="35dp"
android:layout_marginLeft="200dp"
android:layout_marginTop="5dp"
android:background="@drawable/shape1"
android:text="獲取驗證碼"
android:textColor="#FFFFFF"
android:textSize="10sp" />
</RelativeLayout>
<View />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="45dp"
android:minHeight="50.0dip"
android:paddingLeft="14.0dip"
android:paddingRight="12.0dip" >
<ImageView
android:layout_width="23.0dip"
android:layout_height="23.0dip"
android:layout_centerVertical="true"
android:src="@drawable/lock" />
<EditText
android:id="@+id/et_register_password_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="@null"
android:hint="請輸入新密碼"
android:paddingLeft="15dip"
android:paddingTop="8dp"
android:textColorHint="#BEBEBE"
android:textSize="20sp" />
</RelativeLayout>
<View />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:scaleX="0.8"
android:scaleY="0.8" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="我同意"
android:textSize="18sp" />
<TextView
android:id="@+id/user_protocol"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:gravity="center"
android:text="用戶協議及隱私條款"
android:textColor="#FE8B4A"
android:textSize="18sp" />
</LinearLayout>
<Button
android:id="@+id/bt_register_id"
android:layout_width="245dp"
android:layout_height="45dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="14dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:background="@drawable/shape2"
android:gravity="center"
android:text="注 冊"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:paddingTop="5dp"
android:text="您也可以直接登錄"
android:textColor="#BEBEBE"
android:textSize="20sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:baselineAligned="false"
android:gravity="center"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@drawable/weixin_login" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="微信登錄"
android:textColor="#BEBEBE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@drawable/weibo_login" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="微博登錄"
android:textColor="#BEBEBE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<Button
android:layout_width="60dp"
android:layout_height="60dp"
android:background="@drawable/qq_login" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="QQ登錄"
android:textColor="#BEBEBE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
這個 Activity 有四個值得學習的點:倒計時按鈕、兩個自定義 Handler、弱引用防內存洩露、線程取消機制。
字段聲明與初始化:
public class RegisterActivity extends Activity implements OnClickListener {
private EditText etRegisterName;
private EditText etCode;
private EditText etPassword;
private Button btCode;
private Button btRegister;
private TextView tvUserProtocol;
private Button btRegisterLoginBack;
private String userName;
private String passWord;
public boolean isChange = false;
private boolean tag = true;
private int i = 60;
Thread thread = null;
private String valicationCode; // 客戶端輸入的驗證碼
private static String serverValicationCode; // 服務端返回的驗證碼
private Map<String, Object> registerParams = new HashMap<String, Object>();
private Map<String, Object> codeParams = new HashMap<String, Object>();
private String regisgerStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
initView();
}
public void initView() {
etRegisterName = (EditText) findViewById(R.id.et_register_username_id);
etCode = (EditText) findViewById(R.id.et_register_code_id);
etPassword = (EditText) findViewById(R.id.et_register_password_id);
btCode = (Button) findViewById(R.id.bt_getcode_id);
btRegister = (Button) findViewById(R.id.bt_register_id);
tvUserProtocol = (TextView) findViewById(R.id.user_protocol);
btRegisterLoginBack = (Button) findViewById(R.id.register_back_login);
btCode.setOnClickListener(this);
btRegister.setOnClickListener(this);
tvUserProtocol.setOnClickListener(this);
btRegisterLoginBack.setOnClickListener(this);
}
點擊事件分發,以及 60 秒倒計時的實現:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_getcode_id:
if (!isvalidate()) break;
btCode.setText("獲取驗證碼");
btCode.setClickable(true);
isChange = true;
changeBtnGetCode(); // 先啟動倒計時,防止重複點擊
getValidateCode(); // 再異步請求
break;
case R.id.bt_register_id:
register();
break;
case R.id.user_protocol:
startActivity(new Intent(this, UserProtocolActivity.class));
break;
case R.id.register_back_login:
this.finish();
break;
}
}
private void changeBtnGetCode() {
thread = new Thread() {
@Override
public void run() {
if (tag) {
while (i > 0) {
i--;
if (RegisterActivity.this == null) {
break; // 頁面已銷毀則跳出,避免洩露
}
RegisterActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
btCode.setText("獲取驗證碼(" + i + ")");
btCode.setClickable(false);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
tag = false;
}
i = 60;
tag = true;
if (RegisterActivity.this != null) {
RegisterActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
btCode.setText("獲取驗證碼");
btCode.setClickable(true);
}
});
}
}
};
thread.start();
}
請求驗證碼與提交注冊:
public boolean getValidateCode() {
String name = etRegisterName.getText().toString().trim();
String code = etCode.getText().toString().trim();
if (name.equals("")) {
Toast.makeText(this, "請輸入用戶名或手機號!", Toast.LENGTH_SHORT).show();
return false;
} else {
userName = name;
valicationCode = code;
new Thread(codeRunnable).start();
}
return true;
}
public void register() {
// 1. 判斷輸入是否有效
// 2. 判斷驗證碼是否正確(防止用戶自己亂填)
// 3. 發起注冊
if (isValid()) {
if (valicationCode.equals(serverValicationCode)) {
new Thread(sRunnable).start();
} else {
Toast.makeText(this, "輸入的驗證碼不正確!", Toast.LENGTH_SHORT).show();
}
}
}
弱引用 Handler:非靜態內部類的 Handler 會隱式持有外部 Activity 的引用,如果 Activity 已銷毀而消息延遲未處理,就會造成內存洩露。把 Handler 聲明為 static 並用 WeakReference 持有 Activity,是標準解法:
/** 獲取驗證碼用的 Handler */
private static class CodeHandler extends Handler {
private final WeakReference<RegisterActivity> mActivity;
public CodeHandler(RegisterActivity activity) {
mActivity = new WeakReference<RegisterActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
RegisterActivity activity = mActivity.get();
if (activity != null) { // 弱引用可能已被回收,必須判空
switch (msg.what) {
case 1:
serverValicationCode = (String) msg.obj;
break;
case -1:
Toast.makeText(activity, "獲取驗證碼失敗!", Toast.LENGTH_SHORT).show();
break;
case 0:
Toast.makeText(activity, "哎呀,出錯啦..", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
private final CodeHandler codeHandler = new CodeHandler(this);
/** 獲取驗證碼的子線程 */
private Runnable codeRunnable = new Runnable() {
@Override
public void run() {
Message msg = new Message();
Map<String, Object> map = new HashMap<String, Object>();
map.put("jbPhone", userName);
AppContext appContext = (AppContext) getApplication();
try {
serverValicationCode = appContext.getCode(map);
if (serverValicationCode.equals("")) {
msg.what = -1;
} else {
msg.what = 1;
msg.obj = serverValicationCode;
}
} catch (AppException e) {
msg.what = 0;
e.printStackTrace();
}
codeHandler.sendMessage(msg);
}
};
注冊用的 Handler 與線程,結構完全一致,只是 what 值語義不同:
private static class MyHandler extends Handler {
private final WeakReference<RegisterActivity> mActivity;
public MyHandler(RegisterActivity activity) {
mActivity = new WeakReference<RegisterActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
RegisterActivity activity = mActivity.get();
if (activity != null) {
switch (msg.what) {
case 1:
Toast.makeText(activity, "注冊成功!", Toast.LENGTH_SHORT).show();
activity.finish();
break;
case -1:
Toast.makeText(activity, "注冊失敗!", Toast.LENGTH_SHORT).show();
break;
case -2:
Toast.makeText(activity, "該號已經注冊!", Toast.LENGTH_SHORT).show();
break;
case 0:
Toast.makeText(activity, "哎呀,出錯啦..", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
private final MyHandler mHandler = new MyHandler(this);
private Runnable sRunnable = new Runnable() {
@Override
public void run() {
Message msg = new Message();
AppContext appContext = (AppContext) getApplication();
try {
regisgerStatus = appContext.register(registerParams);
if (regisgerStatus.equals("true")) {
msg.what = 1;
msg.obj = regisgerStatus;
} else if (regisgerStatus.equals("1")) {
msg.what = -2; // 已注冊
} else if (regisgerStatus.equals("false")) {
msg.what = -1;
}
} catch (AppException e) {
msg.what = 0;
e.printStackTrace();
}
mHandler.sendMessage(msg);
}
};
提交前的完整校驗:
public boolean isValid() {
userName = etRegisterName.getText().toString().trim();
valicationCode = etCode.getText().toString().trim();
passWord = etPassword.getText().toString().trim();
if (userName.equals("")) {
Toast.makeText(this, "用戶名不能為空!", Toast.LENGTH_SHORT).show();
return false;
}
if (valicationCode.equals("")) {
Toast.makeText(this, "驗證碼不能為空!", Toast.LENGTH_SHORT).show();
return false;
}
if (!serverValicationCode.equals(valicationCode)) {
Toast.makeText(this, "驗證碼錯誤", Toast.LENGTH_SHORT).show();
return false;
}
if (passWord.equals("")) {
Toast.makeText(this, "密碼不能為空!", Toast.LENGTH_SHORT).show();
return false;
} else if (passWord.length() < 6) {
Toast.makeText(this, "密碼至少6位!", Toast.LENGTH_SHORT).show();
return false;
}
registerParams.put("username", userName);
registerParams.put("psd", passWord);
return true;
}
先輸入一個號碼注冊:

手機收到的驗證碼短信:

注冊完成的提示:

這套代碼寫於 2015 年,思路清晰但有些做法已經過時,列幾點供參考:
1. 用 ViewModel + LiveData 取代 Handler。Handler 通信需要自己定義 what 常量、自己判空、自己處理線程切換,LiveData 天然是生命週期感知的,Activity 銷毀時自動取消訂閱,連弱引用都不用操心。
2. 驗證碼校驗不應在客戶端做。示例把服務端返回的驗證碼存在靜態變量裡再本地比對,這在安全上是站不住腳的——靜態變量在多進程或應用重啟後會丟失,而且等於把驗證碼明文暴露給了設備。規範做法是客戶端只負責把用戶輸入提交給服務端,由服務端校驗並返回結果。
3. 密碼不能明文傳輸。必須全程走 HTTPS,並考慮加鹽哈希,避免任何形式的明文存儲或傳送。
4. 倒計時可以用 CountDown。原生的 CountDown 或者 Kotlin 協程的 delay 循環都比手寫 Thread + sleep 更簡潔,也不容易出錯。
Java 變數觀念與命名規範解析
變數是什麼 變數是程式中用來儲存資料的命名空間。透過宣告變數,可以指定資料型別、變數名稱與儲存位置,之後即可讀取或修改其中的值。 宣告與賦值 宣告變數時需指定資料型別與
Android Notification 用法總整理:四種建立方式與版本演進
手機來了簡訊而你沒點開,狀態欄上方會留一個小圖示提醒你——這就是 Notification。想在自己的應用裡做類似的事,就得把 Notification 這套 API 摸
Android 應用本地化:讓同一支 App 說多國語言
一支上架的 Android 應用,可能被義大利的學生、西班牙的通勤族、日本的上班族同時打開。要讓每個人都覺得「這 App 是為我做的」,本地化(Localization)
Android Intent 啟動其他應用的實現方法
Intent 除了可以在同一個應用內切換 Activity,也可以用來啟動其他應用。最常見的方式是透過 ComponentName 明確指定目標應用的套件名稱與啟動 Ac