Android - 登入系統:登入頁面


Android端:(使用HTTP POST實現)

public class login extends AppCompatActivity {/**登入用**/
    private CheckBox remembercheck;//判斷使用者有沒有勾選記住帳號密碼
    private EditText username, password;//使用者的帳號密碼欄位
    private Button login,register,forgot;//登入按鈕,創建按鈕,忘記密碼按鈕
    private String LOGIN_URL;/**目前暫定用在同一個router下傳資料**/
    public static String hostip;             //獲取裝置IP
    public static String hostmac;           //獲取裝置MAC
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        LOGIN_URL = getString(R.string.login_url);
        username = (EditText) findViewById(R.id.accounts);
        password = (EditText) findViewById(R.id.password);
        remembercheck = (CheckBox)findViewById(R.id.auto_save_password);
        login = (Button) findViewById(R.id.login);
        login.setOnClickListener(buttonListener);//login監聽設置
        register = (Button) findViewById(R.id.regist);
        register.setOnClickListener(buttonListener2);//創建帳號監聽設置
        forgot = (Button) findViewById(R.id.forgot);
        forgot.setOnClickListener(buttonListener3);//忘記密碼監聽設置

        /**先從設定檔userinfo分別抓出username和pw兩個字串來看使用者是否曾經設置過**/
        SharedPreferences settings = getSharedPreferences("userinfo",0);
        String nowgetname = settings.getString("username", "");
        username.setText(nowgetname);

        SharedPreferences settings2 = getSharedPreferences("userinfo",0);
        String nowgetpw = settings2.getString("pw","");
        password.setText(nowgetpw);

        hostip = getLocalIpAddress();  //獲取裝置IP
        hostmac = getLocalMacAddress();//獲取裝置MAC
    }
    /**獲取IP >> IPv4的(如果把!inetAddress.isLinkLocalAddress()刪掉,就是IPv6的)**/
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()&&!inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        }
        return null;
    }

    /**獲取MAC**/
    public String getLocalMacAddress() {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /**登入紐是否被按下**/
    private Button.OnClickListener buttonListener = new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(remembercheck.isChecked())/**如果登入紐被按下且記住帳密室被勾選的**/
            {
                /**連接userinfo設定檔,並且找到對應的字串將使用者輸入寫進去**/
                SharedPreferences settings = getSharedPreferences("userinfo", 0);
                settings.edit().putString("username", username.getText().toString()).commit();

                SharedPreferences settings3 = getSharedPreferences("userinfo", 0);
                settings3.edit().putString("pw", password.getText().toString()).commit();
            }
            loginUser();/**呼叫這函式進行使用者資料獲取**/
        }
    };

    private Button.OnClickListener buttonListener2 = new Button.OnClickListener() {/**前往創建會員介面**/
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(login.this,register.class);
            startActivity(intent);
        }
    };

    private Button.OnClickListener buttonListener3 = new Button.OnClickListener() {/**前往忘記密碼查詢介面**/
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(login.this,forgotpw.class);
            startActivity(intent);
        }
    };

    private void loginUser() {/**讀取使用者輸入數據**/
        String name = username.getText().toString().trim().toLowerCase();
        String pd = password.getText().toString().trim().toLowerCase();
        String ip = hostip.trim().toLowerCase();
        String mac = hostmac.trim().toLowerCase();
        login(name, pd, ip, mac);/**獲取資料成功後,開始進行傳送**/
    }

    private void login(String name, String password, String ip, String mac) {
        class RegisterUser extends AsyncTask<String, Void, String> {
            ProgressDialog loading;
            Createmem ruc = new Createmem();/**使用Creatmem.class的功能**/
            @Override
            protected void onPreExecute()
            {
                super.onPreExecute();/**當按下創見鈕,出現提式窗**/
                loading = ProgressDialog.show(login.this, "登入中...",null, true, true);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();/**當提式窗結束,出現登入成功與否的訊息**/
                if(s.equals("登入成功!"))/**當字串比對成功即可登入**/
                {
                    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
                    String id = username.getText().toString();/**將使用者唯一帳號變成字串準被傳去首頁**/
                    Intent intent = new Intent();
                    intent.setClass(login.this,menu.class);
                    intent.putExtra("id",id);
                    startActivity(intent);
                    finish();
                }
                else if(s.equals(""))/**如果沒連接到網路**/
                {
                    String show = "請檢查網路連線!";
                    Toast.makeText(getApplicationContext(), show, Toast.LENGTH_SHORT).show();
                }
                else/**連接到網路 登入有問題**/
                {
                    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            protected String doInBackground(String... params)/**將資料放入hashmap**/
            {
                HashMap<String, String> data = new HashMap<String,String>();
                data.put("name",params[0]);
                data.put("password",params[1]);
                data.put("ip",params[2]);
                data.put("mac",params[3]);
                String result = ruc.sendPostRequest(LOGIN_URL,data);
                return  result;
            }
        }
        RegisterUser ru = new RegisterUser();/**傳送資料**/
        ru.execute(name, password, ip, mac);
    }
}
Android介面布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/login_bg"
    tools:context="project.rmotex.achat.login">

    <ImageView android:id="@+id/image"
        android:background="@drawable/login_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="102dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <LinearLayout
        android:orientation="vertical"
        android:id="@+id/input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="28.0dip"
        android:layout_marginRight="28.0dip"
        android:layout_below="@+id/image">
        <EditText android:textSize="16.0sp"
            android:textColor="#E0E0E0"
            android:textColorHint="#E0E0E0"
            android:id="@+id/accounts"
            android:background="#40000000"
            android:gravity="center_vertical"
            android:paddingLeft="12.0dip"
            android:layout_width="fill_parent"
            android:layout_height="44dp"
            android:maxLines="1"
            android:maxLength="16"
            android:hint="Account"
            android:textStyle="bold"
            android:inputType="textPersonName"/>

        <View android:background="#ffc0c3c4"
            android:layout_width="fill_parent"
            android:layout_height="1.0px"
            android:layout_marginLeft="1.0px"
            android:layout_marginRight="1.0px" />

        <EditText android:textSize="16.0sp"
            android:textColor="#E0E0E0"
            android:textColorHint="#E0E0E0"
            android:id="@+id/password"
            android:background="#40000000"
            android:hint="Password"
            android:textStyle="bold"
            android:gravity="center_vertical"
            android:paddingLeft="12.0dip"
            android:layout_width="fill_parent"
            android:layout_height="44dp"
            android:maxLines="1"
            android:maxLength="16"
            android:inputType="textVisiblePassword" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="#40000000"
            android:text="Sign  In"
            android:textStyle="bold"
            android:id="@+id/login"
            android:paddingTop="5.0dip"
            android:layout_marginLeft="12.0dip"
            android:layout_marginTop="12.0dip"
            android:layout_marginRight="12.0dip"
            android:textSize="20.0sp"
            />

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30.0dip"
            android:layout_marginTop="8.0dip"
            android:layout_marginRight="30.0dip"
            android:layout_below="@id/login"
            android:layout_weight="1" >
            <CheckBox android:textSize="16.0sp"
                android:layout_marginTop="8.0dip"
                android:textColor="#ffffffff"
                android:layout_alignParentLeft="true"
                android:id="@+id/auto_save_password"
                android:background="#00000000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="false"
                android:text="KEEP"
                android:gravity="right|center"
                android:textStyle="bold"
                />

            <Button  android:textSize="16.0sp"
                android:textColor="#ffffffff"
                android:layout_alignParentRight="true"
                android:gravity="left|center"
                android:id="@+id/regist"
                android:background="#00000000"
                android:clickable="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:paddingLeft="18.0dip"
                android:text="Sign Up" />
        </RelativeLayout>

        <Button  android:textSize="12.0sp"
            android:textColor="#ffffffff"
            android:id="@+id/forgot"
            android:background="#00000000"
            android:clickable="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:layout_marginLeft="12.0dip"
            android:layout_marginRight="12.0dip"
            android:text="Forgot    Password?"
            android:layout_gravity="center_horizontal" />
    </LinearLayout>
</RelativeLayout>
這裡使用XAMPP建立的Server,將相對應的PHP放置在htdocs這資料夾底下 
登入用PHP(Server必須先完成與MYSQL的連線)
<?php
/**用於使用者登入系統**/
if($_SERVER['REQUEST_METHOD']=='POST'){//限制條件為POST
 $name = $_POST['name'];
 $password = $_POST['password'];
 if($name == '' || $password == '')
 {
 echo '請確實輸入帳號密碼!';
 }
 else if($name == '')
 {
 echo '請輸入帳號!';
 }
 else if($password == '')
 {
 echo '請輸入密碼!';
 }
 else
 {
 require_once('dbConnect.php');
 $sql = "SELECT * FROM userinfo WHERE name='$name'";//先檢查帳號是否存在
 $check = mysqli_fetch_array(mysqli_query($con,$sql));
 if(isset($check)==false)
 {
 echo '此帳號不存在!';
 }
 else//檢查整個帳戶
 { 
 $sqll = "SELECT * FROM userinfo WHERE name='$name' AND password='$password'";
 $checkk = mysqli_fetch_array(mysqli_query($con,$sqll));
 if(isset($checkk)==false)
 {
  echo '帳號正確,請檢查密碼!';
 }
 else
 {
  echo '登入成功!';
  $sqlll = "UPDATE userinfo SET online = NOT online WHERE name = '$name'";//修改上線狀態
  mysqli_query($con,$sqlll);
 }
 }
 mysqli_close($con);
 }
}
else
{
 echo 'Error';
}
?>

留言