編輯:Android 開發實例
登入畫面幾乎是每個需要帳號的 App 都躲不掉的一關。使用者要在這裡輸入帳號與密碼,App 則負責把資料送出去驗證、處理錯誤、並且防止有心人士暴力猜密碼。本章就從零把這幾件事做完。
畫面上需要兩個 EditText:一個收帳號,一個收密碼。密碼欄特別的地方在於必須把 inputType 設為 textPassword,這樣輸入的內容才會顯示成圓點:
<EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout:inputType="textPassword" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
接著放一顆登入鈕,並用 onClick 屬性指定按下後要呼叫的方法名稱:
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="login" android:text="@string/Login" />
回到 Java 端,實作 login 方法。用 getText().toString() 取出字串,再用 equals() 比對:
EditText username = (EditText)findViewById(R.id.editText1); EditText password = (EditText)findViewById(R.id.editText2); public void login(View view){ if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){ //correcct password }else{ //wrong password }
只做驗證還不夠。若允許無限次嘗試,等於把門敞開讓人慢慢試。常見做法是給一個計數器,每失敗一次就減一,歸零時直接停用登入鈕:
int counter = 3; counter--; if(counter==0){ //disble the button, close the application e.t.c }
正式環境裡,這種限制更應該放在伺服器端做(搭配鎖定時間、逐步拉長等待間隔),因為改寫 App 就能重置本地計數器。下面的範例先把 UI 流程跑通。
這個範例做出一個只允許三次嘗試的登入界面,超過就鎖住按鈕。可在實機或模擬器上執行。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案,命名為 LoginScreen,Target SDK 對到最新版 SDK。 |
| 2 | 修改 src/MainActivity.java,加入驗證與計數邏輯。 |
| 3 | 修改 res/layout/activity_main.xml,加入帳號、密碼、登入鈕與剩餘次數顯示。 |
| 4 | 修改 res/values/string.xml,加入所需字串。 |
| 5 | 執行 App 並在裝置上驗證。 |
主活動 src/com.yiibai.loginscreen/MainActivity.java:
package com.example.loginscreen; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private EditText username=null; private EditText password=null; private TextView attempts; private Button login; int counter = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); username = (EditText)findViewById(R.id.editText1); password = (EditText)findViewById(R.id.editText2); attempts = (TextView)findViewById(R.id.textView5); attempts.setText(Integer.toString(counter)); login = (Button)findViewById(R.id.button1); } public void login(View view){ if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){ Toast.makeText(getApplicationContext(), "Redirecting...", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show(); attempts.setBackgroundColor(Color.RED); counter--; attempts.setText(Integer.toString(counter)); if(counter==0){ login.setEnabled(false); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
版面配置 res/layout/activity_main.xml:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://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" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="18dp" android:text="@string/hello_world" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="50dp" android:text="@string/username" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView2" android:layout_marginLeft="32dp" android:layout_toRightOf="@+id/textView2" android:ems="10" > <requestFocus /> </EditText> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/textView2" android:layout_marginTop="38dp" android:text="@string/password" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView3" android:layout_alignLeft="@+id/editText1" android:ems="10" android:inputType="textPassword" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText2" android:layout_centerHorizontal="true" android:layout_marginTop="94dp" android:onClick="login" android:text="@string/Login" /> <TextView android:id="@+id/textVew4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_below="@+id/textView3" android:layout_marginLeft="30dp" android:layout_marginTop="48dp" android:text="@string/attempts" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/textView1" android:layout_alignTop="@+id/textView4" android:text="TextView" /> </RelativeLayout>
字串資源 res/values/string.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LoginScreen</string> <string name="action_settings">Settings</string> <string name="hello_world">Login Screen</string> <string name="username">Username:</string> <string name="password">Password:</string> <string name="Login">Login:</string> <string name="attempts">Attempts Left:</string> </resources>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.loginscreen" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.yiibai.loginscreen.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
安裝並啟動 App,會看到這樣的登入畫面:
在帳號欄輸入 admin,密碼欄故意輸入 Nimda(admin 反寫)後按下登入,驗證失敗:
再失敗一次,剩餘次數歸零,登入鈕被停用:
重新開啟 App(計數器隨程序重啟而重置),這次帳號密碼都填 admin,登入成功:
最後補充幾點安全上的提醒:範例把密碼寫死在程式碼裡,只能當教學用途,真實專案請把驗證交給後端、透過 HTTPS 傳遞;密碼欄除了 textPassword,也建議加上 android:inputType="textPassword|textNoSuggestions" 關閉輸入法猜字;帳號欄可設 autoCompleteType 或 importantForAutofill 控制自動填入行為;至於「忘記密碼」與「註冊」入口,則應導向真正的身分復原流程,而不是在本地端重設。
Android 進階:Activity 與 Intent 用法示例
熟悉 Android 開發的人都知道,Android 有 Activity、Service 和 BroadcastReceiver 三大基礎組件,而它們都依賴 Inten
微信公眾平台開發入門實戰:從 SAE 雲端部署到天氣查詢功能
本系列教程以「方倍工作室」這個公眾號作為實操樣本(二維碼附於文末),帶你走一條完整的開發閉環:申請新浪雲計算資源、建立應用與代碼版本、上傳 PHP 代碼、在公眾平台後台開
Android 登入頁面:三機會驗證與按鈕禁用
許多 App 需要登入頁面來保護使用者資料。除了基本的帳號密碼輸入,也可以加入錯誤次數限制,提高安全性。 登入欄位設計 畫面中需要兩個 EditText,一個輸入使用者名
Android JSON 解析入門
JSON 是一種輕量級的資料交換格式,常用於應用程式與伺服器之間傳輸資料。相比 XML,JSON 結構更簡潔,也更容易在 Android 中解析。本文說明 JSON 的基