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

Android 登入畫面實作:介面、驗證與失敗次數鎖定

編輯:Android 開發實例

幾乎每一款需要使用者帳號的應用——社群軟體、雲端服務、內部系統——都得面對同一個問題:怎麼設計一個既好用又安全的登入畫面。本章從版面配置一路做到「三次錯誤就鎖住登入鈕」的保護機制。

第一步:兩個輸入框與一顆按鈕

使用者名稱用一般 EditText 即可,密碼欄位則必須加上 android:inputType="textPassword",這樣輸入的內容才會被遮成圓點,也不會被輸入法記成普通文字:

 <EditText android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<EditText android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPassword" />

接著放一顆登入鈕,並用 android:onClick 指定按下後要呼叫的方法名稱。這個方法必須實作在 Activity 裡,且簽名固定為 public void name(View view):

 <Button android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="login"
    android:text="@string/Login" />

第二步:取出文字並比對

在 Java 端用 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")){
        // 帳密正確
    } else {
        // 帳密錯誤
    }
}

第三步:加上失敗次數鎖

光是比對帳密還不夠。若允許無限次嘗試,暴力破解就只是時間問題。做法是宣告一個計數器,每失敗一次就遞減,歸零時直接停用登入鈕:

 int counter = 3;
counter--;
if(counter == 0){
    // 停用登入鈕、關閉應用等
}

完整範例

以下範例做出一個只給三次機會的登入畫面,剩餘次數會即時顯示在畫面上,用光後登入鈕變灰。可於實機或模擬器測試。

步驟做法
1用 Android Studio 建立專案,命名為 LoginScreen,Target SDK 設為較新版本。
2修改 src/MainActivity.java,加入驗證與計數邏輯。
3修改 res/layout/activity_main.xml,放入輸入框、按鈕與次數顯示。
4修改 res/values/string.xml,補上字串資源。
5執行並在裝置上驗證。

主活動 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) {
        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/textViedw1" 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" />
    <TextView android:id="@+id/textView2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/textViedw1"
        android:layout_marginTop="50dp" android:text="@string/username" />
    <EditText android:id="@+id/editText1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignBottom="@+id/textViedw2"
        android:layout_toRightOf="@+id/textViedw2" android:ems="10" >
        <requestFocus />
    </EditText>
    <TextView android:id="@+id/textViedw3" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/textViedw2"
        android:layout_marginTop="38dp" android:text="@string/password" />
    <EditText android:id="@+id/editText2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignBottom="@+id/textViedw3"
        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/textViedw4" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/textViedw3"
        android:layout_marginTop="48dp" android:text="@string/attempts" />
    <TextView android:id="@+id/textViedw5" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="TextView" />
</RelativeLayout>

字串資源 res/values/string.xml:

 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LoginScreen</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" >
    <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 裝到 AVD 啟動,會看到這個登入畫面:

Android 登入應用範例

在欄位中輸入資料後按下 Login。這裡故意把密碼打錯(帳號 admin、密碼反過來寫),於是收到錯誤提示:

再錯一次,畫面上的剩餘次數歸零,登入鈕同時被停用:

重新開啟 App 讓計數器重置,這次輸入正確的帳號與密碼(都是 admin)並按下登入,就會成功通過:

最後提醒一句:範例中的帳密是寫死在程式碼裡的,只用來示範流程。真實專案請勿這麼做——帳密應存放於伺服器端,並透過 HTTPS 傳輸;示範用的明碼比對只能當作教學骨架。

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