Android Client Implementation Registration, login details (1) _android

Source: Internet
Author: User
Tags gettext md5 object object stub throwable

We are in the development of Android app will inevitably have to deal with the server, especially for user account information registration and login is every Android developers must master skills, this article will be the client registration/login function of the implementation analysis, not to the place also please point out.

Here we only discuss how the client requests the server for registration, and the sequence of actions taken by the server after receiving the client request is not within the scope of this article, which is interesting for you to refer

Request Server

The client typically uses post requests (carrying parameters) to the server when registering and logging user information. Take the volley framework request server as an example, the real interaction with the server is the following code:

Stringrequest request=new stringrequest (method.post, URL, new listener<string> () {

 //request successful
 @Override Public
 void Onresponse (String s) {
 //Execute request successful callback
 callback.onsuccess ()
 }

 }, new Errorlistener () {

 //Request error
 @Override public
 void Onerrorresponse (Volleyerror volleyerror) {
 //callback
 that failed to execute request Callback.onfailure ()
 }
 }) {

 //Carry Parameters (Map collection)
 @Override
 protected map<string, string> Getparams () throws Authfailureerror {return
 parames;
 }
 };

 Adds a request to the request queue
 Volley.newrequestqueue (context). Add (Request);

Of course, we should set the appropriate callback method when requesting the server to succeed or fail, so that we can do some operation.
callback.onsuccess ()//Request a successful callback
1. Save the User registration information (SP neutralization application)
2. Jump to Main Page

callback.onfailure ()//request failed callback

1. Prompt for error message

The following through a specific demo to introduce
(Statement: This demo for the Ford teacher It Blue Leopard App code intercept)

Note: when interacting with the server, we must make a request in accordance with the required interfaces and rules, where the server in the IT Blue Panther app is used, and the server registration interface data format is as follows

1.url:http://www.itlanbao.com/api/app/users/user_register_handler.ashx

2. Parameter description
Nickname must have a nickname.
Email must have a mailbox
Password must have a password.
Accesstoken must have a signature MD5 (nickname+email+password+ "both platform agreed public key")

3. Request method: POST

4. Return value format:

 Success
 {
 "ret": 0,
 "Errcode": 0,
 "MSG": "Interface Invoke Success",
 "data": {
 "userid": "16489",
 "email": " Nnn@aaa.com ",
 " nickname ":" Duss ",
 " Userhead ":" Http://img.itlanbao.com/avatar.png "
 } 
 }

 failed
 {
 "ret": 1,
 "Errcode": 1,
 "MSG": "Interface call failed"
 }

Demo Demo

Main implementation code (demo will be given at the end of the article)

1. In the registration page (registeractivity), click on the registration button

 Registbtn.setonclicklistener (new Button.onclicklistener () {@Override public void on
 Click (View v) {//TODO auto-generated Method Stub//get user input String Nick = Loginnick.gettext (). toString ();
 String emailstr = Email.gettext (). toString ();
 String passwordstr = Password.gettext (). toString (); if (! Textutils.isempty (Nick) &&! Textutils.isempty (EMAILSTR) &&! Textutils.isempty (PASSWORDSTR)) {if (Utils.isemail (EMAILSTR)) {//Verify that the mailbox format is compliant//
  Call the Getregistdata () method in Requestapidata for registration, incoming user-entered nicknames, mailboxes, passwords, and bean objects and callback objects that parse the data (callback to itself) Requestapidata.getinstance (). Getregistdata (Nick, Emailstr, Passwordstr, Analyticalregistinfo.class,
 Registeractivity.this);
 else {toast.maketext (registeractivity.this, "Enter mailbox Error", Toast.length_short). Show ();
 } else {Toast.maketext (registeractivity.this, "input information incomplete", Toast.length_short). Show ();

}
 }
 }); 

Note: In this registration method, the last parameter we pass in is the callback object, where we pass in the registeractivity itself, so it needs to implement the

Httpresponecallback interface
 requestapidata.getinstance (). Getregistdata (Nick, Emailstr, Passwordstr,
  Analyticalregistinfo.class, Registeractivity.this);

2. Request the server's callback interface (Httpresponecallback)

 Public interface Httpresponecallback {public
 void Onresponestart (String apiname);

 /**
 * This callback takes effect only when the download method is invoked to download data
 * 
 * @param apiname
 * @param count
 * @param
 Current * * Public
 void Onloading (String apiname, Long count, long current);

 public void onsuccess (String apiname, object);

 public void OnFailure (string apiname, Throwable t, int errorno, string strMsg);



3. Network interface Class (Requestapidata)

 public class Requestapidata {private static requestapidata instance = NULL;

 Private Httpresponecallback mcallback = null;
 Create interface object public static Requestapidata getinstance () {if (instance = null) {instance = new Requestapidata ();
 return instance; /** * 4.6 Registered user interface * @param nickname nickname * @param email address * @param password password * @param clazz data returned resolution Object * @param CA Llback Callback * Special attention should be given to the parameter position cannot be changed according to the document * Request mode: POST/public void Getregistdata (string nickname,string Email, string password
 , Class<analyticalregistinfo> Clazz, Httpresponecallback callback) {mcallback = callback; This is the only indication of each interface String Tagurl = urlconstance.key_regist_info;//Registration interface//keep registered information in map (must be consistent with server) hashmap<string,
 string> parameter = new hashmap<string, string> ();
 Parameter.put ("nickname", nickname);
 Parameter.put ("email", email);

 Parameter.put ("password", password);
 Splicing parameter information, nicknames, mailboxes, passwords, public keys, and MD5 for encryption StringBuilder builder = new StringBuilder ();
 Builder.append (nickname); BuiLder.append (email);
 Builder.append (password);

 Builder.append (Urlconstance.public_key);

 Parameter.put (Urlconstance.accesstoken_key,md5util.getmd5str (builder.tostring ()));

 Call the Requestmanager post method, requesting the server Requestmanager.post (urlconstance.app_url,tagurl, parameter, Clazz, callback);

 }
}

 4. Network request processing Class (Requestmanager)

 public class Requestmanager {private static requestqueue mrequestqueue;


 private static Imageloader Mimageloader;  Private synchronized static void Initrequestqueue () {if (Mrequestqueue = null) {//Create a request queue (using the volley framework) Mrequestqueue
 = Volley.newrequestqueue (Itlanbaolibapplication.getinstance ()); /** * Add request to request queue * @param request * @param tag/private static void Addrequest (Request<?> request, Ob
 Ject tag) {if (tag!= null) {Request.settag (tag);
 } mrequestqueue.add (Request); /** * POST Request data * * @param app_url Common interface prefix http://www.itlanbao.com/api/app/* @param tag_url interface name, Eg:users/user_re GISTER_HANDLER.ASHX (Registration Interface) * @param parameter request parameter Encapsulation Object * @param clazz return Data encapsulation object, if NULL, return String * @param callback interface back  Tune monitor/public static <T> void post (final string app_url, final string tag_url, final hashmap<string, string> parameter, class<t> clazz, Final Httpresponecallback callback) {//Send POST Request Server post (App_url, Tag_url, parAmeter, Clazz, Callback, Priority.normal); /** * POST Request data * * @param app_url path * @param URL Interface name * @param parameter Request parameter Encapsulation Object * @param clazz return Data Encapsulation object, if passed NULL, direct return String * @param callback Interface Callback Listener * @param priority specify interface request thread priority/public static <T> void post (final Str ing app_url, final String URL, final hashmap<string, string> parameter, final class<t> clazz, final httpresp
 Onecallback callback, Priority Priority) {if (callback!= null) {Callback.onresponestart (URL);//callback Request Start}//Initialize request queue

 Initrequestqueue (); Stitching the common interface prefix and interface name//eg: Stitching into a registered interface Http://www.itlanbao.com/api/app/users/user_register_Handler.ashx StringBuilder
 Builder = new StringBuilder (App_url);

 Builder.append (URL);

 {//Check if the current network is available final networkutils networkutils = new Networkutils (Itlanbaolibapplication.getinstance ()); if (!networkutils.isnetworkconnected () && Android.os.Build.VERSION.SDK_INT >) {if (callback!= null) {C Allback.onfailure (URL, null, 0, "network error");Callback request failed return;
 }}/** * Use the volley framework to actually request server * Method.post: Request for POST * builder.tostring (): Requested link * LISTENER&LT;STRING&GT;: monitor/
  Stringrequest request = new Stringrequest (Method.post, builder.tostring (), new listener<string> () {@Override public void Onresponse (String response) {//TODO auto-generated method stub try {if (Response!= null &&
  Callback!= null) {Gson Gson = new Gson ();

  Callback request succeeded, incoming URL and parsed object callback.onsuccess (URL, Gson.fromjson (response, clazz)); } catch (Exception e) {//Todo:handle Exception if (callback!= null) {//Callback request failed--Parse exception callback.onfailure (u
  RL, E, 0, "analytic anomaly");
  Return '}} ', new Errorlistener () {///Request error listening @Override public void Onerrorresponse (Volleyerror error) {if (Callbac
  K!= null) {if (Error!= null) {callback.onfailure (URL, error.getcause (), 0, Error.getmessage ());
  else {callback.onfailure (URL, null, 0, ""); }}}) {//post requested parameter information protected map<stRing, string> Getparams () {return getpostapiparmes (parameter);

 }
 };
 Add a request to the request queue addrequest (request, URL); * * * POST parameter * * TS: Timestamp sign: interface signature parms = parm[0]+ by document parameters ... + parm[n-1] Sign = * MD5 (parms+ "both platforms agreed public key") * * pri
 vate Static Apiparams getpostapiparmes (final hashmap<string, string> parameter) {Apiparams API = new Apiparams ();
 For (entry<string, string> entry:parameter.entrySet ()) {Api.with (Entry.getkey (), Entry.getvalue ());
 } return API;

 }

}

 5. The callback method executes after the request server succeeds/fails, and the callback object we pass in is itself (registeractivity), so now we go back to the Register page

 @Override public void Onresponestart (String apiname) {//TODO auto-generated Method stub Toast.maketext (registeracti
 Vity.this, "requesting data ...", Toast.length_short). Show (); @Override public void onloading (String apiname, Long count, long current) {Toast.maketext (Registeractivity.this, "L 
 Oading ... ", Toast.length_short). Show (); @Override public void onsuccess (String apiname, Object object) {//TODO auto-generated Method Stub//register interface if (URL Constance.KEY_REGIST_INFO.equals (Apiname)) {if (object!= null && object instanceof analyticalregistinfo) {Ana
 Lyticalregistinfo info = (analyticalregistinfo) object;
 String Successcode = Info.getret ();
  The request succeeds if (Successcode.equals (constant.key_success)) {Userbaseinfo Baseuser = new Userbaseinfo ();
  Baseuser.setemail (Info.getemail ());
  Baseuser.setnickname (Info.getnickname ());
  Baseuser.setuserhead (Info.getuserhead ());
  Baseuser.setuserid (String.valueof (Info.getuserid ())); Itlanbaoapplication.getinstance (). SetBaseuser (Baseuser);
  Userpreference.save (keyconstance.is_user_id, String.valueof (Info.getuserid ()));
  Userpreference.save (Keyconstance.is_user_account, Info.getemail ());


  Userpreference.save (Keyconstance.is_user_password, Password.gettext (). toString ());
  Intent Intent = new Intent (registeractivity.this, Mainactivity.class);

  RegisterActivity.this.startActivity (Intent);

  Toast.maketext (Registeractivity.this, "Registration successful ...", Toast.length_short). Show ();

 RegisterActivity.this.finish ();
 else {toast.maketext (Registeractivity.this, registration failed, Toast.length_short). Show (); @Override public void OnFailure (string apiname, Throwable t, int errorno, string strMsg) {Toast.maketext (
 Registeractivity.this, "failure", Toast.length_short). Show (); 
 }

Demo Download Address: Http://xiazai.jb51.net/201611/yuanma/Androidlogindemo (jb51.net). rar

At this point, the Android client registration function is realized, the next will introduce the login and automatic login implementation, please pay attention.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.