編輯:關於 Android 程式設計
1 概述
從這篇開始,正式進入簡易版微信的開發。在深入之前,想先聊聊個人對 Android 程式開發的一些理解,未必正確,僅是自家心得。Android 開發不像大學時寫 C 語言主控台程式那樣,得從 main 一路把邏輯寫出來,大部分控制都由自己實作。事實上,Android 已經替我們準備好了一套程式運行框架,我們只要往框架裡填入所需的內容即可,而這些內容主要圍繞四大元件——Activity、Service、ContentProvider、BroadCast。在這四大元件中,可以實現前端界面顯示與後端資料處理的相關控制邏輯。
前端界面顯示主要涉及:元件的生命週期回呼管理、為視圖(View)註冊事件監聽器、集合型態視圖的資料適配器(Adapter)、不同視窗之間的跳轉等等。後端資料交互則主要涉及:非同步任務(AsyncTask)、Handler/Message、網路編程(HTTP 或 Socket)、資料庫操作(SQLiteOpenHelper 或 ContentProvider)等等。所以對初學者而言,學 Android 主要就是學會框架中每個類別的作用與用法。
好,進入本文主題。第一次使用微信這類應用時,首先就是註冊與登入,本文就來實現這兩個基本功能。由於剛接觸 Android 開發,需要了解的基礎知識不少,我們將透過這兩個功能學習以下幾個重點:
Layout 布局:用來製作使用者界面。Android 使用 XML 檔描述 UI 布局,類似 HTML+CSS 的元件方式。對後端工程師來說,依照 UI 設計稿布局或定制控件,或許是學前端最大的障礙之一。關於 UI 布局,本文先起個頭,隨著後續深入,我們會慢慢熟悉;至於自行開發一個視圖(View),也是 Android 開發的難點,後續再逐步深入。
Activity 概念與生命週期:布局完成後,要把 UI 顯示出來,就得靠 Activity 元件——它負責界面顯示與使用者互動。Activity 應該是 Android 最重要的元件——一個應用可以沒有其他三大元件,卻不能沒有 Activity——它類似 Windows 編程中的視窗,沒有視窗又如何與使用者互動?
登入、註冊功能的實現:談完 Activity 後,就要透過它加入我們需要的邏輯。Android 應用通常是 C(客戶端)/S(服務端)結構,登入與註冊包含客戶端與伺服器端兩部分邏輯,我們將在後續章節介紹。
最後總結本篇內容並預告下一篇,就讓我們開啟 Android 學習的第二課吧!
2 Android 的 MVC 結構
學習一門新技術時,我們很少思考「這門技術重點該學什麼、該怎麼學」。多數人常一頭栽進知識點的汪洋,最後連自己學會了什麼都搞不清楚。比如學 Java,若一上來就從變數命名、表達式、控制流到物件導向一路學下去,對完全的新手或許合適;但若你已經會 C 或 C++,有些知識點其實可以跳過。以我自己為例,長期使用 C++,所以一開始就直接學 I/O 流、集合類這些常用知識,很快就能寫出小程式,有空再回頭研究多執行緒、垃圾回收與原始碼。
學 Android 也一樣,先要弄清楚該學什麼,這就必須從更高的層次來看它。從架構上說,和許多 UI 框架一樣,Android 採用主流的 MVC 結構,這是相當成熟的前端框架。MVC 結構如下圖:

MVC 結構分為三部分:
控制器(Controller):接收使用者輸入,透過事件分發機制決定接收者。這部分在 Android 中已有框架完成,我們只需在 Activity 中為 View 註冊特定監聽器即可,監聽器的具體邏輯由我們自己撰寫;而且只需知道有這麼一回事,用到時查 API 即可。
模型(Model):主要實現業務邏輯處理與資料更新。這部分應是 Android 編程的重點,四大元件中的 Service、ContentProvider 都與 Model 相關,此外資料儲存(如資料庫、檔案)也屬於 Model 範疇,是學習的重中之重。
視圖(View):負責顯示模型資料。在 Android 中就是使用 View 進行 UI 布局,當框架提供的部件不滿足需求時,就得依需求重寫 View,實現想要的效果。
這樣劃分之後,我們大致就知道一個 Android 軟體由哪些部分組成、彼此如何互動,以及框架已為我們實現了哪些功能、哪些需要我們擴展,學習起來才有的放矢。
3 Layout 布局及分析
說到做軟體 UI,博主曾有過一段痛苦的回憶。大三上學期修完《資料庫系統概論》後,老師要求用 ASP.NET 做一個網站。當時我做的是一個線上購書系統,不懂怎麼製作網頁界面,就在 Visual Studio 裡用拖拽控件的方式硬湊,最後雖然把系統折騰出來了(過程可說十分煎熬),但界面實在讓人提不起購買的慾望。經歷這一出後,我對前端界面一度產生恐懼與排斥。不過工作之後,慢慢接觸到軟體 UI 的設計與實現,自己也動手做了一些布局,這種恐懼才逐漸消退。這裡想分享一句心得:想做出漂亮的 UI 布局,不是靠拖拽控件拖出來的。當然,對初學者而言,用拖拽的方式入門 Android 框架也未嘗不可。
Android 製作 UI 界面有兩種方式:
(1)透過 XML 設定檔的方式,博主稱之為「聲明式布局」:把要顯示的控件及其顯示方式宣告在 XML 中,再透過 Activity 的 setContentView 把布局描述交給 Activity;
(2)透過 Java 類別來添加布局控件並設定相關屬性,博主稱之為「命令式布局」。
第一種(聲明式)通常用於變化不大的 UI;第二種(命令式)通常用於執行時不斷變化的界面。本篇要實現的登入、註冊採用聲明式布局,因此本小節只介紹聲明式,命令式留待後續用到時再詳述。
好了,理論就先談到這,寫程式的最怕聽一大堆理論,來看看登入與註冊界面的實現效果吧(也許還不完美,之後邊學邊改)。首先是登入頁面(也是打開軟體後的第一頁):

註冊頁面:

註冊、登入之間的互動以及登入成功後的界面(登入成功後畫面是空白的,就不另外貼出來了)。圖片有點糊,湊合著看~

下面以登入界面的程式碼,看看 Android 如何實現界面布局,整份 UI 布局程式碼如下(路徑:$res/layout/activity_login.xml):
<?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"> <!--Top Panel--> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:background="@color/colorTopPanelBackground" android:gravity="center" android:text="@string/string_login" android:textSize="@dimen/font_size_large" android:textColor="@color/colorSpecialWhite" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="@dimen/activity_horizontal_margin" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="50dip" android:orientation="horizontal" android:layout_marginTop="50dp"> <TextView android:layout_width="50dip" android:layout_height="50dip" android:gravity="center_vertical|right" android:text="+86" android:textColor="@color/colorSpecialBlack" android:textSize="@dimen/font_size_medium" /> <EditText android:id="@+id/edt_login_cellphone_number" android:layout_width="0dp" android:layout_height="50dip" android:layout_weight="1" android:layout_marginLeft="25dp" android:background="@null" android:hint="你的手機號碼" android:textSize="@dimen/font_size_medium" android:textColorHint="@color/colorHintText"/> </LinearLayout> <View android:id="@+id/dvd_login_username" android:layout_width="match_parent" android:layout_height="2px" android:background="@color/colorDefault" /> <LinearLayout android:layout_width="match_parent" android:layout_height="50dip" android:orientation="horizontal"> <TextView android:layout_width="50dip" android:layout_height="50dip" android:gravity="center_vertical|right" android:text="@string/string_pass_word" android:textColor="@color/colorSpecialBlack" android:textSize="@dimen/font_size_medium" /> <EditText android:id="@+id/edt_login_password" android:layout_width="0dp" android:layout_height="50dip" android:layout_weight="1" android:layout_marginLeft="25dp" android:background="@null" android:inputType="textPassword" android:textSize="@dimen/font_size_medium" android:hint="填入密碼" android:textColorHint="@color/colorHintText"/> </LinearLayout> <View android:id="@+id/dvd_login_password" android:layout_width="match_parent" android:layout_height="2px" android:background="@color/colorDefault" /> <Button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="@dimen/button_general_height" android:layout_marginTop="50dip" android:background="@drawable/btn_common_selector" android:text="@string/string_login" android:textSize="@dimen/font_size_medium" android:textColor="@color/colorSpecialWhite"/> <Button android:id="@+id/btn_register" android:layout_width="match_parent" android:layout_height="@dimen/button_general_height" android:layout_marginTop="20dip" android:background="@drawable/btn_implicit_selector" android:text="@string/string_register" android:textSize="@dimen/font_size_medium" /> </LinearLayout> </LinearLayout>
上述程式碼一層套一層,最終形成一個樹狀結構,如下圖:

圖中每個矩形就是一個控件(或稱視圖),每個控件都有一整套與它相關的外觀屬性(類似 Web 編程中的 CSS),控制著顯示效果。下面從根節點開始逐一深入分析。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
根節點是一個布局控件,這裡用的是線性布局(LinearLayout),其他還有相對布局(RelativeLayout)與幀布局(FrameLayout)。布局控件的作用就是堆疊(專業點說叫布置 Arrange)控件:線性布局顧名思義只能沿單一方向(水平 horizontal 或垂直 vertical)堆疊,如上述程式碼中 android:orientation 屬性即用來說明它是水平橫向的線性布局;相對布局比線性布局複雜些,控件之間的位置不再受限於單一方向,而是依據既有的其他控件來決定;幀布局則是層層疊疊的方式。此外,上述程式碼中還有 android:layout_width 與 android:layout_height,用來描述控件的寬與高,這是每個控件都必須填的屬性。這兩個屬性的值是一個長度值,可用像素(px)、點(pt)、設備獨立像素(dp 或 dip);這裡用的是特殊值 match_parent——匹配父視窗,即長或寬與父視窗相同;另一個特殊值 wrap_content——內容包裹,即長或寬與內容相符,內容佔多大,控件就多大。
<!--Top Panel--> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:background="@color/colorTopPanelBackground" android:gravity="center" android:text="@string/string_login" android:textSize="@dimen/font_size_large" android:textColor="@color/colorSpecialWhite" />
這是第一個可視控件,即文本視圖(TextView),可以看到有許多屬性控制它的外觀,如前述的寬高、android:background 描述背景色(很多 Android 控件都有此屬性),這裡採用引用資源的方式,可提高程式碼的可維護性,顏色資源定義在 $res/values/colors.xml 中(可理解為程式設計裡的常量)。除了背景色,我們還定義了其他顏色資源,後面的程式碼會用到:
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#11D31D</color> <color name="colorPrimaryDark">#308E0E</color> <color name="colorAccent">#FF4081</color> <!--color in default status--> <color name="colorDefault">#999999</color> <!--color in active status--> <color name="colorActive">@color/colorPrimary</color> <!--background color of top panel--> <color name="colorTopPanelBackground">#525252</color> <!--color of hint text--> <color name="colorHintText">#DDDDDD</color> <!--some special color--> <color name="colorSpecialBlack">#000000</color> <color name="colorSpecialWhite">#FFFFFF</color> </resources>
接下來 android:gravity 用來描述控件中內容的對齊方式,此處就是 TextView 中文本的對齊方式(居中)。再來 android:text 用來指定文本內容,這裡同樣引用另一個資源檔中的字串資源,位於 $res/values/strings.xml,專門定義字串常量:
<resources> <string name="app_name">MyChat</string> <!-- TODO: Remove or change this placeholder text --> <string name="hello_blank_fragment">Hello blank fragment</string> <!--constant string used in resource--> <string name="string_nick_name">昵稱</string> <string name="string_pass_word">密碼</string> <string name="string_login">登錄</string> <string name="string_register">注冊</string> <string name="string_dialog_title">提示</string> <string name="string_dialog_tips_prefix">正在</string> <string name="string_dialog_tips_suffix">,請稍等...</string> </resources>
接下來的屬性分別定義了文本大小與顏色,同樣使用引用資源的方式,文本大小定義在 $res/values/dimens.xml 中,這個檔案專門定義與尺寸有關的資源:
<resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> <dimen name="horizontal_line_margin">20dp</dimen> <dimen name="contact_image_width">50dp</dimen> <dimen name="contact_image_height">50dp</dimen> <dimen name="context_image_top_buttom_margin">15dp</dimen> <dimen name="activity_registration_vertical_margin">16dp</dimen> <!--following tags define font size--> <dimen name="font_size_medium">16sp</dimen> <dimen name="font_size_small">14sp</dimen> <dimen name="font_size_large">18sp</dimen> <dimen name="font_size_xsmall">12sp</dimen> <dimen name="font_size_xlarge">20sp</dimen> <!--following tags defi--> <dimen name="button_general_height">40dp</dimen> </resources>
到這裡,第一個控件——頂部標題 TextView——就分析完了。可以看到,為了提高可維護性與復用性,我們把大多數屬性值都定義在對應的資源檔中。接下來的控件分析就簡單多了,又是一個布局控件,裡面存放一個登入表單:
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="@dimen/activity_horizontal_margin" android:orientation="vertical">
這裡沒什麼特別,唯一要注意的是新增了 android:layout_margin 屬性,用來描述控件的上、下、左、右外邊距:

四邊的外邊距也可以獨立控制,對應屬性分別為 android:layout_marginTop、android:layout_Buttom、android:layout_Left 與 android:layout_Right。接下來是表單內容區,先要顯示兩個輸入框及說明文字,輸入框用 EditText,說明文字用 TextView,它們水平排列,所以需要用線性布局包起來:
<LinearLayout android:layout_width="match_parent" android:layout_height="50dip" android:orientation="horizontal" android:layout_marginTop="50dp"> <TextView android:layout_width="50dip" android:layout_height="50dip" android:gravity="center_vertical|right" android:text="+86" android:textColor="@color/colorSpecialBlack" android:textSize="@dimen/font_size_medium" /> <EditText android:id="@+id/edt_login_cellphone_number" android:layout_width="0dp" android:layout_height="50dip" android:layout_weight="1" android:layout_marginLeft="25dp" android:background="@null" android:hint="你的手機號碼" android:textSize="@dimen/font_size_medium" android:textColorHint="@color/colorHintText"/> </LinearLayout> <View android:id="@+id/dvd_login_username" android:layout_width="match_parent" android:layout_height="2px" android:background="@color/colorDefault" /> <LinearLayout android:layout_width="match_parent" android:layout_height="50dip" android:orientation="horizontal"> <TextView android:layout_width="50dip" android:layout_height="50dip" android:gravity="center_vertical|right" android:text="@string/string_pass_word" android:textColor="@color/colorSpecialBlack" android:textSize="@dimen/font_size_medium" /> <EditText android:id="@+id/edt_login_password" android:layout_width="0dp" android:layout_height="50dip" android:layout_weight="1" android:layout_marginLeft="25dp" android:background="@null" android:inputType="textPassword" android:textSize="@dimen/font_size_medium" android:hint="填入密碼" android:textColorHint="@color/colorHintText"/> </LinearLayout> <View android:id="@+id/dvd_login_password" android:layout_width="match_parent" android:layout_height="2px" android:background="@color/colorDefault" />
上述程式碼大部分屬性前面都介紹過了,新增的只有三個。android:inputType 用來描述輸入框的輸入類型,這裡用的是密碼類型 textPassword,會把輸入的字母變成一個個小圓點:

對於 EditText,還有其他輸入類型(input type):
(1)text
(2)textEmailAddress
(3)textUri
(4)number
(5)phone
設定不同類型,執行時彈出的軟鍵盤也不同,例如設為 textEmailAddress 時,鍵盤上會多一個 @ 符號:

當設為 number 或 phone 時,軟鍵盤則變成:

剩下兩個屬性都與提示文字有關,分別為 android:hint 與 android:textColorHint,用來描述提示文字的內容與顏色:

上圖輸入框下方有一條綠色橫線,做法是設定一個高度 2px、寬度 match_parent 的 View(一般 1px 就夠,但這裡覺得不明顯,所以設為 2px):
<View android:id="@+id/dvd_login_password" android:layout_width="match_parent" android:layout_height="2px" android:background="@color/colorDefault" />
再來是兩個 Button,分別觸發登入、註冊:

程式碼如下:
<Button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="@dimen/button_general_height" android:layout_marginTop="50dip" android:background="@drawable/btn_common_selector" android:text="@string/string_login" android:textSize="@dimen/font_size_medium" android:textColor="@color/colorSpecialWhite"/> <Button android:id="@+id/btn_register" android:layout_width="match_parent" android:layout_height="@dimen/button_general_height" android:layout_marginTop="20dip" android:background="@drawable/btn_implicit_selector" android:text="@string/string_register" android:textSize="@dimen/font_size_medium" />
這裡有一點特殊:背景用了一種稱為選擇器(selector)的資源——因為按鈕按下與彈起時背景不同,如下為按下狀態:

與前面彈起狀態對比,背景色變深了,這就用上選擇器資源了。該資源位於 $res/color 目錄下(注意:建立 Android 專案時預設沒有這個資料夾,需手動建立),內容如下:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="https://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:color="#308E0E"/> <!-- pressed --> <item android:color="#11D31D"/> <!-- default --> </selector>
分別指定了按下與預設的顏色。到此,登入布局頁面就講完了,註冊頁面與登入大同小異,就不再贅述。最後分享幾點個人經驗:
(1)布局其實就兩步:先確定用什麼控件;再為控件配上屬性;
(2)屬性這麼多,書寫時最好有個次序,我的做法是:先 id,再寬高,接著是布局相關屬性(如內外邊距),然後背景色、內容對齊方式,最後才是文字內容、顏色、大小——由外到內、從通用到特殊。
(3)盡量把屬性值定義在資源檔中,方便後期維護與復用。
3 Activity 概念及其生命週期
第 2 小節詳細講了登入界面及相關 View 與外觀屬性。定義在 XML 中的 UI 只是靜態檔,需要載入應用後才能被渲染顯示,這就要用到本節的 Activity。本節主要總結 Activity 的概念與生命週期。
3.1 什麼是 Activity
許多 Android 書籍對 Activity 的闡述多少有些零散,這裡拋磚引玉,總結一下自己的理解:
(I)從 MVC 模式看,Activity 相當於 Controller——一邊接收使用者請求,一邊把請求分發到各處理單元,在 Android 應用中起核心作用:

圖中標出了透過 Activity 啟動各大元件的 API,這些 API 都定義在 Activity 中。當然這只是簡化模型,實際接收請求時可能還會用到其他元件,後續再深入學習。
(II)從設計模式看,Activity 可看作門面模式(Facade Pattern),內部聚合了許多元件:

對內封裝複雜元件,對外提供簡單接口,同時也能獨立取得元件實例,這正是門面模式的典型應用。要注意的是,Activity 繼承自 ContextThemeWrapper,其中聚合了 Resource,可透過它訪問程式資源;而 ContextThemeWrapper 又繼承自 ContextWrapper,透過它可取得 ContentResolver 等元件。
(III)從開發者角度看,Activity 是一個狀態機,定義了管理其生命週期的一系列事件,透過這些事件可保存應用狀態,將在 3.2 說明。
3.2 Activity 的生命週期
Activity 的生命週期是每本 Android 書必講的重點。Android 四大元件都有生命週期,但 Activity 最複雜,下圖是來自 Android SDK 文件的回呼順序:

這張圖有點像作業系統裡的行程狀態轉換圖。初看會覺得有點亂,其實理清楚後,無非就是四條狀態變換路徑:
(I)中間垂直方向走下來:Activity launched → onCreate → onStart → onResume → running → onPause → onStop → onDestroy → Activity shutdown
註:這種情況是用戶打開首頁、做完事後退出應用。
(2)內圈:Activity launched → onCreate → onStart → onResume → running → onPause → User navigates to the activity → onResume → ……
(3)中圈:Activity launched → onCreate → onStart → onResume → running → onPause → onStop → User navigates to the activity → onRestart → onResume → ……
(4)外圈:Activity launched → onCreate → onStart → onResume → running → onPause [→ onStop →] App Process Killed → User navigates to the activity → onCreate → onRestart → onResume → ……
註:加方括號的 onStop 表示可有可無,也就是外圈有兩條路線——在 Pause 狀態被 Kill,或在 Stop 狀態被 Kill。
之所以有這麼多狀態變換路徑,正是因為使用者互動複雜。以下對回呼做幾點說明:
(1)onPause 與 onResume 對應,onStop 與 onStart/onRestart 對應;
(2)執行過 onPause、onStop、onDestroy 的 Activity 在記憶體不足時都可能被 Kill,優先級不同:Destroy 最先被 Kill,其次 Stop,實在沒轍才 Kill Pause 狀態的;
(3)被 Kill 的 Activity 若使用者重新回到,需再次呼叫 onCreate 重建實例;
(4)onStop 不一定總會被執行,所以保存狀態資料的程式碼應寫在 onPause 中;
(5)各回呼的呼叫時機與對應狀態如下:

4 登入功能的實現詳解
從這節起正式進入登入、註冊功能的實現。由於採 C/S 結構,分為客戶端與伺服器端,兩者之間以 HTTP 協議互動:

4.1 客戶端邏輯
客戶端繼承 Activity 得到 LoginActivity 與 RegisterActivity 兩個子類,註冊的客戶端程式碼與登入類似,不再贅述。下面看 LoginActivity 的邏輯,主要重寫了 onCreate:先載入 UI(activity_login.xml),再為註冊、登入兩個按鈕添加監聽器:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mLoginButton = (Button) findViewById(R.id.btn_login); mRegisterButton = (Button) findViewById(R.id.btn_register); mEditTextUserName = (EditText) findViewById(R.id.edt_login_cellphone_number); mEditTextPassword = (EditText) findViewById(R.id.edt_login_password); mDvdPassword = findViewById(R.id.dvd_login_password); mDvdUserName = findViewById(R.id.dvd_login_username); mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("OnClick", "Enter the click callback of Login Button"); String cellphone_number = mEditTextUserName.getText().toString().trim(); String pass_word = mEditTextPassword.getText().toString().trim(); Map<String, String> params = new HashMap<String, String>(); params.put("url", LOGIN_PATH); params.put("cellphone_number", cellphone_number); params.put("pass_word", pass_word); new LoginAsyncTask(LoginActivity.this).execute(params); } }); mRegisterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Enter into the register activity Intent intent = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(intent); } }); mEditTextPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { mDvdPassword.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); } else { mDvdPassword.setBackgroundColor(getResources().getColor(R.color.colorDefault)); } } }); mEditTextUserName.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { mDvdUserName.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); } else { mDvdUserName.setBackgroundColor(getResources().getColor(R.color.colorDefault)); } } }); }
說明:
(1)第 5 行呼叫 setContentView 設定 UI,這句必須先寫,否則後面的 View 都取不到;
(2)第 7~12 行透過 findViewById 取得對應 ID 的 View,這些 ID 在編寫 UI 時指定;
(3)以匿名內部類為登入按鈕註冊 Click 監聽器,在監聽器內部先取出手機號與密碼,再透過非同步任務(AsyncTask)送到伺服器端:
public class LoginAsyncTask extends AsyncTask<Map<String, String>, Void, Boolean> { private ProgressDialog mDialog; private Context mContext; public LoginAsyncTask(Context context) { mDialog = new ProgressDialog(context); mDialog.setTitle("提示信息"); mDialog.setMessage("正在登錄,請稍等..."); mContext = context; } @Override protected Boolean doInBackground(Map<String, String>... params) { String url = params[0].get("url"); Map<String, String> mapParams = new Hashtable(); for (Map.Entry<String, String> entry : params[0].entrySet()) { if (!entry.getKey().equals("url")) { mapParams.put(entry.getKey(), entry.getValue()); } } String result = null; try { result = HttpUtil.sendPostRequest(url, mapParams, "utf-8"); } catch (Exception e) { e.printStackTrace(); } return result.equals("True") ? true : false; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (mDialog.isShowing()) mDialog.dismiss(); if (result) { // jump to Main page Intent intent = new Intent(mContext, MainActivity.class); mContext.startActivity(intent); } else { Toast.makeText(mContext, "登錄失敗!", Toast.LENGTH_LONG).show(); } } }
非同步任務顧名思義就是開啟一個執行緒來跑邏輯。在 Android 中,顯示界面與接收輸出的程式碼都在 UI 執行緒執行,因此 UI 執行緒一般不允許阻塞,否則會影響使用者體驗。對耗時操作,需交由非 UI 執行緒執行,完成後再由 UI 執行緒更新結果。這裡提交帳號密碼的網路操作較耗時,若直接在 UI 執行緒執行會導致阻塞,引起 Android Not Responding 異常(下圖,很熟悉吧),所以得放進非同步任務:

Android 框架在 Java 多執行緒之上引入了 AsyncTask 與 Handler/Message/Loop 兩種機制。AsyncTask 是抽象類,必須重寫 doInBackground(運行於背景執行緒,此處即發送網路請求並解析結果);另有 onPreExecute 與 onPostExecute 也重要,兩者運行於 UI 執行緒,前者在 doInBackground 之前調用(如顯示進度框),後者在之後調用(更新 UI 結果)。上述程式碼依回傳結果判斷登入是否成功,成功則跳轉 MainActivity,失敗則彈出 Toast 提示。
另外,AsyncTask 是模板類,有三個參數:第一個(如 Map<String, String>)指定 doInBackground 的入參型別;第三個(如 Boolean)是 doInBackground 的回傳型別,同時是 onPostExecute 的入參型別;第二個指定進度值型別(如 Integer、Float),此處沒用到進度條刻度,故設為 Void。
發送命令、取得伺服器回傳結果的邏輯,我們封裝在 HttpUtil 類中:
public class HttpUtil { public static String sendPostRequest( String path, Map<String, String> params, String encoding) throws Exception { StringBuilder sb = new StringBuilder(); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append("="); sb.append(URLEncoder.encode(entry.getValue(), encoding)); sb.append("&"); } sb.deleteCharAt(sb.length() - 1); } HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(sb.toString().getBytes()); os.flush(); if (conn.getResponseCode() == 200) { String result = StreamTool.readStream(conn.getInputStream()); return result; } else { return null; } } }
主要邏輯是把參數用 & 串接起來,寫入 HttpURLConnection 並發送到伺服器端;回傳後讀取狀態碼,若為 200 表示成功,此時透過 StreamTool 從串流中讀取回傳值:
public class StreamTool { public static String readStream(InputStream stream) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = in.readLine()) != null) { sb.append(line); System.out.println("===>" + line); } return sb.toString(); }
至此,登入功能的客戶端程式碼就寫完了。有興趣的朋友可以下載源碼:https://pan.baidu.com/s/1skHOkxB(有空也去註冊個 github,感覺用百度雲分享太 low,^__^)。
4.2 伺服器端邏輯
伺服器端就是寫兩個 Servlet:LoginServlet 與 RegisterServlet。我們把資料庫查詢與修改封裝在 UserDAOImpl 中,兩個 Servlet 呼叫其接口來驗證與添加用戶,下面仍以 LoginServlet 為例。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); // parse parameters from client. String cellphone_number = request.getParameter("cellphone_number"); String pass_word = request.getParameter("pass_word"); PrintWriter writer = response.getWriter(); try { UserDAOInterface userDAO = new UserDAOImpl(); User user = userDAO.queryByCellPhoneNumber(cellphone_number); if (user != null && user.getPassWord().equals(pass_word)) { writer.append("True"); System.out.println("True"); } else { writer.append("False"); System.out.println("False"); } } catch (SQLException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } }
簡單說:取得客戶端提交的手機號與密碼,用手機號從資料庫查對應用戶記錄,若用戶存在且密碼正確則回傳 True,否則回傳 False。伺服器端本質就是 Java Web 編程,這裡不再細究。
5 總結
總結一下,本文我們學習了 Layout 布局及用來展示布局的 Activity,對相關 View 做了較詳細分析,也介紹了 Activity 的概念與生命週期回呼,最後說明了登入功能的程式碼實現(註冊與登入類似,有興趣可下載源碼研究)。
下一次將介紹好友列表功能的實現,敬請期待^__^
源碼下載:https://xiazai.jb51.net/201606/yuanma/MyChat(jb51.net).rar
以上就是本文的全部內容,希望對大家的學習有所幫助。
Android 自定義控件實作:高仿美團下拉刷新動畫
美團的下拉刷新包含三個狀態。第一是「下拉刷新」(pull to refresh),此時一個綠色橢圓會隨著下拉距離動態縮放;第二是「放開刷新」(release to re
Android TabLayout 選項卡布局實戰入門教程
TabLayout 是許多人開發 Android 應用時經常會用到的組件,本文就帶大家一起動手玩轉這個官方選項卡控件,希望對正在學習的朋友有所幫助。 為什麼選擇 Tab
華為榮耀Note8智能短信全解鎖 六大貼心功能設定教學
曾幾何時,短信幾乎被微信、QQ這類即時通訊軟件擠到了角落裡,如今它剩下的用處,不外乎收收驗證碼、充值提醒或者訂票通知。不過華為榮耀Note8的登場,卻讓這項「老功能」重新
從零搭建 C# Android 開發環境:JDK、SDK、VS2015 與 Xamarin 完整圖文
工欲善其事,必先利其器。不論你打算用 C# + VS2015 還是 Java + Eclipse 開發 Android,都得先把 JDK 與 Android SDK 裝好