安卓開發--帳號登入、切換、自動登入功能實現。

來源:互聯網
上載者:User

      這是自己的第一篇部落格。這篇部落格的內容是實現安卓開發當中的帳號登入等相關功能,用到的主要是HttpClient、HttpPost等相關類。      1.首先是登陸功能:

package com.example.net;import java.io.IOException;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;public class Login {public static final String BASE_URL = "http://202.202.43.205/zwyd/";public static final String LOGIN_URL = "user.php";public static final String LOGIN_OK_STR = "ok";public static final String PWD_ERR_STR = "pwd_err";public static final String NO_USER_STR = "unknown";public static final int LOGIN_OK = 1;public static final int PWD_ERR = 4;public static final int NO_USER = 5;static String result = "";public static int login(String number, String passWord)throws ClientProtocolException, IOException {// TODO Auto-generated method stubint loginStatus = -1;System.out.println(number + "" + passWord);List<NameValuePair> params = new ArrayList<NameValuePair>();//初始化一個儲存索引值對對象的Listparams.add(new BasicNameValuePair("usrName", number));params.add(new BasicNameValuePair("usrPwd", passWord));// 注意此處key需要與伺服器端key相對應HttpClient httpClient = new DefaultHttpClient();//獲得一個預設httpClient對象HttpPost post = new HttpPost(BASE_URL + LOGIN_URL);//構造HttpPost對象postpost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//佈建要求參數HttpResponse response = httpClient.execute(post);//發送post請求返回HttpResponse對象if (response.getStatusLine().getStatusCode() == 200) {result = EntityUtils.toString(response.getEntity());//獲得返回的結果System.out.println(result);}if (result.equals(LOGIN_OK_STR)) {//登入成功loginStatus = LOGIN_OK;} else if (result.equals(PWD_ERR_STR)) {//密碼錯誤loginStatus = PWD_ERR;} else if (result.equals(NO_USER_STR)) {//無該使用者loginStatus = NO_USER;}return loginStatus;}}
        通過該類的靜態方法login(String number, String passWord)可以實現帳號登入,並根據返回結果判斷登陸結果。        最需要注意的是

       2.在MainActivity中實現登入需要在非同步任務中進行,因為登入會阻塞UI線程。
/** * 非同步任務驗證帳號 *  * @author Administrator *  */class NetWork extends AsyncTask<String, Integer, Integer> {ProgressDialog pd;/** * 執行任務後調用 */@Overrideprotected void onPostExecute(Integer result) {// TODO Auto-generated method stubsuper.onPostExecute(result);pd.dismiss();// 消失switch (flag) {case LOGIN_OK:toOther();break;case PWD_ERR:Toast.makeText(MainActivity.this, "密碼錯誤!", Toast.LENGTH_SHORT).show();share.edit().clear().commit();// 清除所有資料break;case NO_USER:Toast.makeText(MainActivity.this, "使用者不存在!", Toast.LENGTH_SHORT).show();share.edit().clear().commit();// 清除所有資料break;}}/** * 執行任務之前調用 */@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();pd = new ProgressDialog(MainActivity.this);pd.setMessage("正在驗證,請稍後……");pd.setIndeterminate(false);// 在最大值最小值中移動pd.setCancelable(true);// 可以取消pd.show();}/** * 執行任務中調用更新任務進度 */@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);}/** * 執行任務 */@Overrideprotected Integer doInBackground(String... arg0) {// TODO Auto-generated method stubtry {flag = Login.login(userNum, userPass);} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}}
  
      3.記住密碼自動登入。主要用到的是SharedPreference儲存帳號及密碼下次啟動程式自動登入。      獲得SharedPreference對象:
        share = getSharedPreferences("user", MODE_PRIVATE);// 擷取對象
      儲存帳號及密碼:
        share.edit().putString("usrName", userNum).commit();// 儲存帳號資料        share.edit().putString("usrPwd", userPass).commit();
       自動登入:
number.setText(userNum);pass.setText(userPass);        new NetWork().execute();

       4.切換帳號。主要是清除儲存的密碼,跳轉到登陸介面。
/** * 切換帳號 */public void change(View v) {share.edit().clear().commit();// 清除所有資料Intent intent = new Intent();intent.setClass(NextActivity.this, MainActivity.class);startActivity(intent);this.finish();}


      好了,以上就是全部功能的實現。當然網路編程不要忘了在AndroidManifest中添加許可權。     還有以上功能需要配合伺服器,伺服器用php開發。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.