我们都知道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中进行简单的处理,就可以实现了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
Android SDK Manager 不知为什么突然打不开了?看这里
监听Android系统发出的插入SD卡并且已正确安装(识别)时发出的广播
RecyclerView三种常用效果的实现方法-android-kotlin
Android Studio app启动错误 Error running :Default Activity not found
网友评论