編輯:關於Android編程
我們都知道Android應用軟件基本上都會用到登錄注冊功能,那麼對一個一個好的登錄注冊模塊進行封裝就勢在必行了。這裡給大家介紹一下我的第一個項目中所用到的登錄注冊功能的,已經對其進行封裝,希望能對大家有幫助,如果有什麼錯誤或者改進的話希望各位可以指出。
我們都知道登錄注冊系列功能的實現有以下幾步:
大體的流程如下
對於需要獲取用戶登錄狀態的操作,先判斷用戶是否已經登錄。
如果用戶已經登錄,則繼續後面的操作,否則,跳轉到登錄頁面進行登錄。
如果已經有賬號,則可以直接登錄,或者可以直接選擇第三方平台授權登錄。
如果還沒有賬號,則需要先進行賬號注冊,注冊成功後再登錄;也可以不注冊賬號,通過第三方平台授權進行登錄。
如果有賬號,但忘記密碼,可以重置密碼,否則直接登錄。
好了,一個登錄注冊系列的常用功能就是以上這五點了,大體流程也已經知道了,接下來讓我們一個一個的實現它們。
注冊功能的實現
注冊時一般通過手機或者郵箱來注冊,這裡我選擇利用手機號來注冊;且注冊時通常需要接收驗證碼,這裡通過第三方的Mob平台的短信SDK來實現,第三方賬號授權也是利用Mob的ShareSDK來實現的。注冊完成後由客戶端將注冊信息提交至服務端進行注冊,提交方式為HTTP的POST請求方式。
SignUpActivity.Java
package com.example.administrator.loginandregister.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; import com.example.administrator.loginandregister.R; import com.example.administrator.loginandregister.utils.RegexUtils; import com.example.administrator.loginandregister.utils.ToastUtils; import com.example.administrator.loginandregister.utils.VerifyCodeManager; import com.example.administrator.loginandregister.views.CleanEditText; import org.json.JSONException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Timer; import java.util.TimerTask; /** * Created by JimCharles on 2016/11/27. */ public class SignUpActivity extends Activity implements OnClickListener { private static final String TAG = "SignupActivity"; // 界面控件 private CleanEditText phoneEdit; private CleanEditText passwordEdit; private CleanEditText verifyCodeEdit; private CleanEditText nicknameEdit; private Button getVerifiCodeButton; private Button createAccountButton; private VerifyCodeManager codeManager; String result = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); initViews(); codeManager = new VerifyCodeManager(this, phoneEdit, getVerifiCodeButton); } /** * 通過findViewById,減少重復的類型轉換 * * @param id * @return */ @SuppressWarnings("unchecked") public final <E extends View> E getView(int id) { try { return (E) findViewById(id); } catch (ClassCastException ex) { Log.e(TAG, "Could not cast View to concrete class.", ex); throw ex; } } private void initViews() { getVerifiCodeButton = getView(R.id.btn_send_verifi_code); getVerifiCodeButton.setOnClickListener(this); createAccountButton = getView(R.id.btn_create_account); createAccountButton.setOnClickListener(this); phoneEdit = getView(R.id.et_phone); phoneEdit.setImeOptions(EditorInfo.IME_ACTION_NEXT);// 下一步 verifyCodeEdit = getView(R.id.et_verifiCode); verifyCodeEdit.setImeOptions(EditorInfo.IME_ACTION_NEXT);// 下一步 nicknameEdit = getView(R.id.et_nickname); nicknameEdit.setImeOptions(EditorInfo.IME_ACTION_NEXT); passwordEdit = getView(R.id.et_password); passwordEdit.setImeOptions(EditorInfo.IME_ACTION_DONE); passwordEdit.setImeOptions(EditorInfo.IME_ACTION_GO); passwordEdit.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // 點擊虛擬鍵盤的done if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) { try { commit(); } catch (IOException | JSONException e1) { e1.printStackTrace(); } } return false; } }); } private void commit() throws IOException, JSONException { String phone = phoneEdit.getText().toString().trim(); String password = passwordEdit.getText().toString().trim(); if (checkInput(phone, password)) { // TODO:請求服務端注冊賬號 createAccountButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //android4.0後的新的特性,網絡數據請求時不能放在主線程中。 //使用線程執行訪問服務器,獲取返回信息後通知主線程更新UI或者提示信息。 final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { //提示讀取結果 Toast.makeText(SignUpActivity.this, result, Toast.LENGTH_LONG).show(); if (result.contains("成")){ Toast.makeText(SignUpActivity.this, result, Toast.LENGTH_LONG).show(); ToastUtils.showShort(SignUpActivity.this, "注冊成功......"); } else{ final Intent it = new Intent(SignUpActivity.this, LoginActivity.class); //你要轉向的Activity Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { startActivity(it); //執行 } }; timer.schedule(task, 1000); //1秒後 } } } }; // 啟動線程來執行任務 new Thread() { public void run() { //請求網絡 try { Register(phoneEdit.getText().toString(),passwordEdit.getText().toString(),nicknameEdit.getText().toString()); } catch (IOException | JSONException e) { e.printStackTrace(); } Message m = new Message(); m.what = 1; // 發送消息到Handler handler.sendMessage(m); } }.start(); } }); } } private boolean checkInput(String phone, String password) { if (TextUtils.isEmpty(phone)) { // 電話號碼為空 ToastUtils.showShort(this, R.string.tip_phone_can_not_be_empty); } else { if (!RegexUtils.checkMobile(phone)) { // 電話號碼格式有誤 ToastUtils.showShort(this, R.string.tip_phone_regex_not_right); } else if (password == null || password.trim().equals("")) { Toast.makeText(this, R.string.tip_password_can_not_be_empty, Toast.LENGTH_LONG).show(); }else if (password.length() < 6 || password.length() > 32 || TextUtils.isEmpty(password)) { // 密碼格式 ToastUtils.showShort(this, R.string.tip_please_input_6_32_password); } else { return true; } } return false; } public Boolean Register(String account, String passWord, String niceName) throws IOException, JSONException { try { String httpUrl="http://cdz.ittun.cn/cdz/user_register.php"; URL url = new URL(httpUrl);//創建一個URL HttpURLConnection connection = (HttpURLConnection)url.openConnection();//通過該url獲得與服務器的連接 connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST");//設置請求方式為post connection.setConnectTimeout(3000);//設置超時為3秒 //設置傳送類型 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Charset", "utf-8"); //提交數據 String data = "&name=" + URLEncoder.encode(niceName, "UTF-8")+"&cardid=" + "&passwd=" +passWord+ "&money=0"+ "&number=" + account;//傳遞的數據 connection.setRequestProperty("Content-Length",String.valueOf(data.getBytes().length)); ToastUtils.showShort(this, "數據提交成功......"); //獲取輸出流 OutputStream os = connection.getOutputStream(); os.write(data.getBytes()); os.flush(); //獲取響應輸入流對象 InputStreamReader is = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(is); StringBuffer strBuffer = new StringBuffer(); String line = null; //讀取服務器返回信息 while ((line = bufferedReader.readLine()) != null){ strBuffer.append(line); } result = strBuffer.toString(); is.close(); connection.disconnect(); } catch (Exception e) { return true; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_send_verifi_code: // TODO 請求接口發送驗證碼 codeManager.getVerifyCode(VerifyCodeManager.REGISTER); break; case R.id.btn_create_account: try { commit(); } catch (IOException | JSONException e) { e.printStackTrace(); } break; default: break; } } }
登錄功能的實現
登錄功能需要在完成注冊以後才能進行,只要提交賬號、密碼等信息至服務器,請求登錄即可,至於第三方登錄功能利用Mob平台的ShareSDK來實現。
LoginActivity.java
package com.example.administrator.loginandregister.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.loginandregister.R; import com.example.administrator.loginandregister.global.AppConstants; import com.example.administrator.loginandregister.utils.LogUtils; import com.example.administrator.loginandregister.utils.ProgressDialogUtils; import com.example.administrator.loginandregister.utils.RegexUtils; import com.example.administrator.loginandregister.utils.ShareUtils; import com.example.administrator.loginandregister.utils.SpUtils; import com.example.administrator.loginandregister.utils.ToastUtils; import com.example.administrator.loginandregister.utils.UrlConstance; import com.example.administrator.loginandregister.utils.Utils; import com.example.administrator.loginandregister.views.CleanEditText; import com.umeng.socialize.bean.SHARE_MEDIA; import com.umeng.socialize.controller.UMServiceFactory; import com.umeng.socialize.controller.UMSocialService; import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener; import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener; import com.umeng.socialize.exception.SocializeException; import org.json.JSONException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import static android.view.View.OnClickListener; /** * Created by JimCharles on 2016/11/27. */ public class LoginActivity extends Activity implements OnClickListener,UrlConstance { private static final String TAG = "loginActivity"; private static final int REQUEST_CODE_TO_REGISTER = 0x001; // 界面控件 private CleanEditText accountEdit; private CleanEditText passwordEdit; private Button loginButton; // 第三方平台獲取的訪問token,有效時間,uid private String accessToken; private String expires_in; private String uid; private String sns; String result = ""; // 整個平台的Controller,負責管理整個SDK的配置、操作等處理 private UMSocialService mController = UMServiceFactory .getUMSocialService(AppConstants.DESCRIPTOR); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initViews(); // 配置分享平台 ShareUtils.configPlatforms(this); } /** * 初始化視圖 */ private void initViews() { loginButton = (Button) findViewById(R.id.btn_login); loginButton.setOnClickListener(this); accountEdit = (CleanEditText) this.findViewById(R.id.et_email_phone); accountEdit.setImeOptions(EditorInfo.IME_ACTION_NEXT); accountEdit.setTransformationMethod(HideReturnsTransformationMethod .getInstance()); passwordEdit = (CleanEditText) this.findViewById(R.id.et_password); passwordEdit.setImeOptions(EditorInfo.IME_ACTION_DONE); passwordEdit.setImeOptions(EditorInfo.IME_ACTION_GO); passwordEdit.setTransformationMethod(PasswordTransformationMethod .getInstance()); passwordEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) { clickLogin(); } return false; } }); } private void clickLogin() { String account = accountEdit.getText().toString(); String password = passwordEdit.getText().toString(); if (checkInput(account, password)) { // TODO: 請求服務器登錄賬號 // Login(account,password); loginButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //android4.0後的新的特性,網絡數據請求時不能放在主線程中。 //使用線程執行訪問服務器,獲取返回信息後通知主線程更新UI或者提示信息。 final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { //提示讀取結果 Toast.makeText(LoginActivity.this, result, Toast.LENGTH_LONG).show(); ToastUtils.showShort(LoginActivity.this, result); if (result.contains("!")) { Toast.makeText(LoginActivity.this, result, Toast.LENGTH_LONG).show(); ToastUtils.showShort(LoginActivity.this, "密碼錯誤......"); } else { final Intent it = new Intent(LoginActivity.this, WelcomActivity.class); //你要轉向的Activity Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { startActivity(it); //執行 } }; timer.schedule(task, 1000); //1秒後 } } } }; // 啟動線程來執行任務 new Thread() { public void run() { //請求網絡 try { Login(accountEdit.getText().toString(),passwordEdit.getText().toString()); } catch (IOException | JSONException e) { e.printStackTrace(); } Message m = new Message(); m.what = 1; // 發送消息到Handler handler.sendMessage(m); } }.start(); } }); } } public Boolean Login(String account, String passWord) throws IOException, JSONException { try { String httpUrl="http://cdz.ittun.cn/cdz/user_login.php"; URL url = new URL(httpUrl);//創建一個URL HttpURLConnection connection = (HttpURLConnection)url.openConnection();//通過該url獲得與服務器的連接 connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST");//設置請求方式為post connection.setConnectTimeout(3000);//設置超時為3秒 //設置傳送類型 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Charset", "utf-8"); //提交數據 String data = "&passwd=" + URLEncoder.encode(passWord, "UTF-8")+ "&number=" + URLEncoder.encode(account, "UTF-8")+ "&cardid=";//傳遞的數據 connection.setRequestProperty("Content-Length",String.valueOf(data.getBytes().length)); ToastUtils.showShort(this, "數據提交成功......"); //獲取輸出流 OutputStream os = connection.getOutputStream(); os.write(data.getBytes()); os.flush(); //獲取響應輸入流對象 InputStreamReader is = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(is); StringBuffer strBuffer = new StringBuffer(); String line = null; //讀取服務器返回信息 while ((line = bufferedReader.readLine()) != null){ strBuffer.append(line); } result = strBuffer.toString(); is.close(); connection.disconnect(); } catch (Exception e) { return true; } return false; } /** * 檢查輸入 * * @param account * @param password * @return */ public boolean checkInput(String account, String password) { // 賬號為空時提示 if (account == null || account.trim().equals("")) { Toast.makeText(this, R.string.tip_account_empty, Toast.LENGTH_LONG) .show(); } else { // 賬號不匹配手機號格式(11位數字且以1開頭) if ( !RegexUtils.checkMobile(account)) { Toast.makeText(this, R.string.tip_account_regex_not_right, Toast.LENGTH_LONG).show(); } else if (password == null || password.trim().equals("")) { Toast.makeText(this, R.string.tip_password_can_not_be_empty, Toast.LENGTH_LONG).show(); } else { return true; } } return false; } @Override public void onClick(View v) { Intent intent = null; switch (v.getId()) { case R.id.iv_cancel: finish(); break; case R.id.btn_login: clickLogin(); break; case R.id.iv_wechat: clickLoginWexin(); break; case R.id.iv_qq: clickLoginQQ(); break; case R.id.iv_sina: loginThirdPlatform(SHARE_MEDIA.SINA); break; case R.id.tv_create_account: enterRegister(); break; case R.id.tv_forget_password: enterForgetPwd(); break; default: break; } } /** * 點擊使用QQ快速登錄 */ private void clickLoginQQ() { if (!Utils.isQQClientAvailable(this)) { ToastUtils.showShort(LoginActivity.this, getString(R.string.no_install_qq)); } else { loginThirdPlatform(SHARE_MEDIA.QZONE); } } /** * 點擊使用微信登錄 */ private void clickLoginWexin() { if (!Utils.isWeixinAvilible(this)) { ToastUtils.showShort(LoginActivity.this, getString(R.string.no_install_wechat)); } else { loginThirdPlatform(SHARE_MEDIA.WEIXIN); } } /** * 跳轉到忘記密碼 */ private void enterForgetPwd() { Intent intent = new Intent(this, ForgetPasswordActivity.class); startActivity(intent); } /** * 跳轉到注冊頁面 */ private void enterRegister() { Intent intent = new Intent(this, SignUpActivity.class); startActivityForResult(intent, REQUEST_CODE_TO_REGISTER); } /** * 授權。如果授權成功,則獲取用戶信息 * * @param platform */ private void loginThirdPlatform(final SHARE_MEDIA platform) { mController.doOauthVerify(LoginActivity.this, platform, new UMAuthListener() { @Override public void onStart(SHARE_MEDIA platform) { LogUtils.i(TAG, "onStart------" + Thread.currentThread().getId()); ProgressDialogUtils.getInstance().show( LoginActivity.this, getString(R.string.tip_begin_oauth)); } @Override public void onError(SocializeException e, SHARE_MEDIA platform) { LogUtils.i(TAG, "onError------" + Thread.currentThread().getId()); ToastUtils.showShort(LoginActivity.this, getString(R.string.oauth_fail)); ProgressDialogUtils.getInstance().dismiss(); } @Override public void onComplete(Bundle value, SHARE_MEDIA platform) { LogUtils.i(TAG, "onComplete------" + value.toString()); if (platform == SHARE_MEDIA.SINA) { accessToken = value.getString("access_key"); } else { accessToken = value.getString("access_token"); } expires_in = value.getString("expires_in"); // 獲取uid uid = value.getString(AppConstants.UID); if (!TextUtils.isEmpty(uid)) { // uid不為空,獲取用戶信息 getUserInfo(platform); } else { ToastUtils.showShort(LoginActivity.this, getString(R.string.oauth_fail)); } } @Override public void onCancel(SHARE_MEDIA platform) { LogUtils.i(TAG, "onCancel------" + Thread.currentThread().getId()); ToastUtils.showShort(LoginActivity.this, getString(R.string.oauth_cancle)); ProgressDialogUtils.getInstance().dismiss(); } }); } /** * 獲取用戶信息 * * @param platform */ private void getUserInfo(final SHARE_MEDIA platform) { mController.getPlatformInfo(LoginActivity.this, platform, new UMDataListener() { @Override public void onStart() { // 開始獲取 LogUtils.i("getUserInfo", "onStart------"); ProgressDialogUtils.getInstance().dismiss(); ProgressDialogUtils.getInstance().show( LoginActivity.this, "正在請求..."); } @Override public void onComplete(int status, Map<String, Object> info) { try { String sns_id = ""; String sns_avatar = ""; String sns_loginname = ""; if (info != null && info.size() != 0) { LogUtils.i("third login", info.toString()); if (platform == SHARE_MEDIA.SINA) { // 新浪微博 sns = AppConstants.SINA; if (info.get(AppConstants.UID) != null) { sns_id = info.get(AppConstants.UID) .toString(); } if (info.get(AppConstants.PROFILE_IMAGE_URL) != null) { sns_avatar = info .get(AppConstants.PROFILE_IMAGE_URL) .toString(); } if (info.get(AppConstants.SCREEN_NAME) != null) { sns_loginname = info.get( AppConstants.SCREEN_NAME) .toString(); } } else if (platform == SHARE_MEDIA.QZONE) { // QQ sns = AppConstants.QQ; if (info.get(AppConstants.UID) == null) { ToastUtils .showShort( LoginActivity.this, getString(R.string.oauth_fail)); return; } sns_id = info.get(AppConstants.UID) .toString(); sns_avatar = info.get( AppConstants.PROFILE_IMAGE_URL) .toString(); sns_loginname = info.get( AppConstants.SCREEN_NAME) .toString(); } else if (platform == SHARE_MEDIA.WEIXIN) { // 微信 sns = AppConstants.WECHAT; sns_id = info.get(AppConstants.OPENID) .toString(); sns_avatar = info.get( AppConstants.HEADIMG_URL) .toString(); sns_loginname = info.get( AppConstants.NICKNAME).toString(); } // 這裡直接保存第三方返回來的用戶信息 SpUtils.putBoolean(LoginActivity.this, AppConstants.THIRD_LOGIN, true); LogUtils.e("info", sns + "," + sns_id + "," + sns_loginname); // TODO: 這裡執行第三方連接(綁定服務器賬號) } } catch (Exception e) { e.printStackTrace(); } } }); } }
忘記密碼功能實現
到這一步其實大家都應該明白了,我用的都是最簡單的方式去實現這些功能,就是通過提交數據給服務器,然後由服務器判斷提交的數據是否正確,正確的話就返回注冊信息,包含賬號、密碼等功能,然後對返回的數據進行操作,修改密碼功能也是這樣,修改返回數據中密碼並重新提交給服務器,這個功能就完成了。
package com.example.administrator.loginandregister.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.administrator.loginandregister.R; import com.example.administrator.loginandregister.utils.RegexUtils; import com.example.administrator.loginandregister.utils.ToastUtils; import com.example.administrator.loginandregister.utils.VerifyCodeManager; import com.example.administrator.loginandregister.views.CleanEditText; import org.json.JSONException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Timer; import java.util.TimerTask; import static android.view.View.OnClickListener; /** * Created by JimCharles on 2016/11/27. */ public class ForgetPasswordActivity extends Activity implements OnClickListener { private static final String TAG = "SignupActivity"; // 界面控件 private CleanEditText phoneEdit; private CleanEditText passwordEdit; private CleanEditText verifyCodeEdit; private Button getVerifiCodeButton; private Button resetButton; private VerifyCodeManager codeManager; String result = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_frogetpwd); initViews(); codeManager = new VerifyCodeManager(this, phoneEdit, getVerifiCodeButton); } /** * 通用findViewById,減少重復的類型轉換 * * @param id * @return */ @SuppressWarnings("unchecked") public final <E extends View> E getView(int id) { try { return (E) findViewById(id); } catch (ClassCastException ex) { Log.e(TAG, "Could not cast View to concrete class.", ex); throw ex; } } private void initViews() { resetButton = getView(R.id.btn_create_account); resetButton.setOnClickListener(this); getVerifiCodeButton = getView(R.id.btn_send_verifi_code); getVerifiCodeButton.setOnClickListener(this); phoneEdit = getView(R.id.et_phone); phoneEdit.setImeOptions(EditorInfo.IME_ACTION_NEXT);// 下一步 verifyCodeEdit = getView(R.id.et_verifiCode); verifyCodeEdit.setImeOptions(EditorInfo.IME_ACTION_NEXT);// 下一步 passwordEdit = getView(R.id.et_password); passwordEdit.setImeOptions(EditorInfo.IME_ACTION_DONE); passwordEdit.setImeOptions(EditorInfo.IME_ACTION_GO); passwordEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // 點擊虛擬鍵盤的done if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) { try { commit(); } catch (IOException | JSONException e) { e.printStackTrace(); } } return false; } }); } private void commit() throws IOException, JSONException { String phone = phoneEdit.getText().toString().trim(); String password = passwordEdit.getText().toString().trim(); if (checkInput(phone, password)) { // TODO:請求服務端注冊賬號 resetButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { //android4.0後的新的特性,網絡數據請求時不能放在主線程中。 //使用線程執行訪問服務器,獲取返回信息後通知主線程更新UI或者提示信息。 final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { //提示讀取結果 Toast.makeText(ForgetPasswordActivity.this, result, Toast.LENGTH_LONG).show(); if (result.contains("成")){ Toast.makeText(ForgetPasswordActivity.this, result, Toast.LENGTH_LONG).show(); ToastUtils.showShort(ForgetPasswordActivity.this, "注冊成功......"); } else{ final Intent it = new Intent(ForgetPasswordActivity.this, LoginActivity.class); //你要轉向的Activity Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { startActivity(it); //執行 } }; timer.schedule(task, 1000); //1秒後 } } } }; // 啟動線程來執行任務 new Thread() { public void run() { //請求網絡 try { Register(phoneEdit.getText().toString(),passwordEdit.getText().toString()); } catch (IOException | JSONException e) { e.printStackTrace(); } Message m = new Message(); m.what = 1; // 發送消息到Handler handler.sendMessage(m); } }.start(); } }); } } private boolean checkInput(String phone, String password) { if (TextUtils.isEmpty(phone)) { // 電話號碼為空 ToastUtils.showShort(this, R.string.tip_phone_can_not_be_empty); } else { if (!RegexUtils.checkMobile(phone)) { // 電話號碼格式有誤 ToastUtils.showShort(this, R.string.tip_phone_regex_not_right); } else if (password.length() < 6 || password.length() > 32 || TextUtils.isEmpty(password)) { // 密碼格式 ToastUtils.showShort(this, R.string.tip_please_input_6_32_password); } else { return true; } } return false; } public Boolean Register(String account, String passWord) throws IOException, JSONException { try { String httpUrl="http://cdz.ittun.cn/cdz/user_register.php"; URL url = new URL(httpUrl);//創建一個URL HttpURLConnection connection = (HttpURLConnection)url.openConnection();//通過該url獲得與服務器的連接 connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST");//設置請求方式為post connection.setConnectTimeout(3000);//設置超時為3秒 //設置傳送類型 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Charset", "utf-8"); //提交數據 String data = "&cardid=" + "&passwd=" +passWord+ "&money=0"+ "&number=" + account;//傳遞的數據 connection.setRequestProperty("Content-Length",String.valueOf(data.getBytes().length)); ToastUtils.showShort(this, "數據提交成功......"); //獲取輸出流 OutputStream os = connection.getOutputStream(); os.write(data.getBytes()); os.flush(); //獲取響應輸入流對象 InputStreamReader is = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(is); StringBuffer strBuffer = new StringBuffer(); String line = null; //讀取服務器返回信息 while ((line = bufferedReader.readLine()) != null){ strBuffer.append(line); } result = strBuffer.toString(); is.close(); connection.disconnect(); } catch (Exception e) { return true; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_cancel: finish(); break; case R.id.btn_send_verifi_code: // TODO 請求接口發送驗證碼 codeManager.getVerifyCode(VerifyCodeManager.RESET_PWD); break; default: break; } } }
記住密碼和自動登錄功能的實現
記住密碼和自動登錄功能可以通過SharedPreferences來實現
調用Context.getSharePreferences(String name, int mode)方法來得到SharePreferences接口,該方法的第一個參數是文件名稱,第二個參數是操作模式。
操作模式有三種:MODE_PRIVATE(私有) ,MODE_WORLD_READABLE(可讀),MODE_WORLD_WRITEABLE(可寫)
SharePreference提供了獲得數據的方法,如getString(String key,String defValue)等
調用SharePreferences的edit()方法返回 SharePreferences.Editor內部接口,該接口提供了保存數據的方法如: putString(String key,String value)等,調用該接口的commit()方法可以將數據保存。
這一部分還沒有進行封裝,簡單的給大家介紹一下利用SharePreferences來實現記住密碼和自動登陸
import android.content.Context; import android.content.SharedPreferences; public class UserInfo { private String USER_INFO = "userInfo"; private Context context; public UserInfo() { } public UserInfo(Context context) { this.context = context; } // 存放字符串型的值 public void setUserInfo(String key, String value) { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); editor.putString(key, value); editor.commit(); } // 存放整形的值 public void setUserInfo(String key, int value) { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); editor.putInt(key, value); editor.commit(); } // 存放長整形值 public void setUserInfo(String key, Long value) { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); editor.putLong(key, value); editor.commit(); } // 存放布爾型值 public void setUserInfo(String key, Boolean value) { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); editor.putBoolean(key, value); editor.commit(); } // 清空記錄 public void clear() { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); editor.commit(); } // 注銷用戶時清空用戶名和密碼 // public void logOut() { // SharedPreferences sp = context.getSharedPreferences(USER_INFO, // Context.MODE_PRIVATE); // SharedPreferences.Editor editor = sp.edit(); // editor.remove(ACCOUNT); // editor.remove(PASSWORD); // editor.commit(); // } // 獲得用戶信息中某項字符串型的值 public String getStringInfo(String key) { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); return sp.getString(key, ""); } // 獲得用戶息中某項整形參數的值 public int getIntInfo(String key) { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); return sp.getInt(key, -1); } // 獲得用戶信息中某項長整形參數的值 public Long getLongInfo(String key) { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); return sp.getLong(key, -1); } // 獲得用戶信息中某項布爾型參數的值 public boolean getBooleanInfo(String key) { SharedPreferences sp = context.getSharedPreferences(USER_INFO, Context.MODE_PRIVATE); return sp.getBoolean(key, false); } } public class MainActivity extends Activity { private Button login, cancel; private EditText usernameEdit, passwordEdit; private CheckBox CK_save, CK_auto; private UserInfo userInfo; private static final String USER_NAME = "user_name"; private static final String PASSWORD = "password"; private static final String ISSAVEPASS = "savePassWord"; private String username; private String password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); userInfo = new UserInfo(this); login = (Button) findViewById(R.id.login_btn); cancel = (Button) findViewById(R.id.unlogin_btn); usernameEdit = (EditText) findViewById(R.id.username); passwordEdit = (EditText) findViewById(R.id.password); CK_save = (CheckBox) findViewById(R.id.savePassword); CK_auto = (CheckBox) findViewById(R.id.autoLogin); // 判斷是否記住了密碼的 初始默認是要記住密碼的 if (userInfo.getBooleanInfo(ISSAVEPASS)) { CK_save.setChecked(true); usernameEdit.setText(userInfo.getStringInfo(USER_NAME)); passwordEdit.setText(userInfo.getStringInfo(PASSWORD)); // 判斷是否要自動登陸 if (userInfo.getBooleanInfo(AUTOLOGIN)) { // 默認是要自動登陸的 CK_auto.setChecked(true); Intent i = new Intent(); i.setClass(MainActivity.this, SecondActivity.class); startActivity(i); } } login.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { username = usernameEdit.getText().toString(); password = passwordEdit.getText().toString(); if (username.equals("liang") && password.equals("123")) { if (CK_save.isChecked()) { userInfo.setUserInfo(USER_NAME, username); userInfo.setUserInfo(PASSWORD, password); userInfo.setUserInfo(ISSAVEPASS, true); } if (CK_auto.isChecked()) { userInfo.setUserInfo(AUTOLOGIN, true); } Intent i = new Intent(); i.setClass(MainActivity.this, SecondActivity.class); startActivity(i); } } }); } }
可見要實現記住密碼和自動登錄功能並不難,只要在登陸的XML布局文件添加兩個Checkbar並對其進行設置,然後在Activity中進行簡單的處理,就可以實現了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。
RadioButton是單選按鈕,多個RadioButton放在一個RadioGroup控件中,也就是說每次只能有1個RadioButton被選中。而CheckBox是多
這是一個Android瀑布流的實現demo。 瀑布流我的實現是定義三個linearlayout,然後向裡面addView(),如果多了會出現oom異常,所以做了一些處理。
上一篇文章中我們講解了關於Android開發過程中常見的內存洩露場景與檢測方案。Android系統為每個應用程序分配的內存是有限的,當一個應用中產生的內存洩漏的情況比較多
引言 網絡一直是我個人的盲點,前一陣子抽出時間學習了一下Volley網絡工具的使用方法,也透過源碼進行了進一步的學習,有一些心得想分享出來。在Android