Android development-account logon, switchover, and automatic logon.

Source: Internet
Author: User

This is my first blog. The content of this blog is to implement account logon and other related functions in Android development. It mainly uses HttpClient, HttpPost, and other related classes. 1. First, the login function:

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> (); // initialize a Listparams object that stores key-value pairs. add (new BasicNameValuePair ("usrName", number); params. add (new BasicNameValuePair ("usrPwd", passWord); // note that the key must correspond to the server key. HttpClient httpClient = new DefaultHttpClient (); // obtain a default httpClient object HttpPost post = new HttpPost (BASE_URL + LOGIN_URL); // construct the HttpPost object postpost. setEntity (new UrlEncodedFormEntity (params, HTTP. UTF_8); // sets the request parameter HttpResponse response = httpClient.exe cute (post); // sends a post request and returns the HttpResponse object if (response. getStatusLine (). getStatusCode () = 200) {result = EntityUtils. toString (response. getEntity (); // obtain the returned result System. out. println (result);} if (result. equals (LOGIN_ OK _STR) {// loginStatus = LOGIN_ OK;} else if (result. equals (PWD_ERR_STR) {// Password error loginStatus = PWD_ERR;} else if (result. equals (NO_USER_STR) {// This user does not have loginStatus = NO_USER;} return loginStatus ;}}
You can use the static login (String number, String passWord) method to log on to an account and determine the logon result based on the returned results. Note that

2. logon in MainActivity must be performed in asynchronous tasks, because logon will block the UI thread.
/*** Asynchronous task verification account ** @ author Administrator **/class NetWork extends AsyncTask <String, Integer, Integer> {ProgressDialog pd; /*** call the task after execution */@ Overrideprotected void onPostExecute (Integer result) {// TODO Auto-generated method stubsuper. onPostExecute (result); pd. dismiss (); // disappears switch (flag) {case LOGIN_ OK: toOther (); break; case PWD_ERR: Toast. makeText (MainActivity. this, "Incorrect password! ", Toast. LENGTH_SHORT ). show (); share. edit (). clear (). commit (); // clear all data break; case NO_USER: Toast. makeText (MainActivity. this, "the user does not exist! ", Toast. LENGTH_SHORT ). show (); share. edit (). clear (). commit (); // clear all data break;}/*** call before executing the task */@ Overrideprotected void onPreExecute () {// TODO Auto-generated method stubsuper. onPreExecute (); pd = new ProgressDialog (MainActivity. this); pd. setMessage ("Verifying. Please wait ...... "); Pd. setIndeterminate (false); // move the pd at the maximum and minimum values. setCancelable (true); // cancel pd. show ();}/*** call the update task progress in the execution task */@ Overrideprotected void onProgressUpdate (Integer... values) {// TODO Auto-generated method stubsuper. onProgressUpdate (values);}/*** execute task */@ 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. Remember the password to log on automatically. It mainly uses SharedPreference to save the account and password and automatically log on to the next Startup Program. Get the SharedPreference object:
Share = getSharedPreferences ("user", MODE_PRIVATE); // get the object
Storage account and password:
Share. edit (). putString ("usrName", userNum ). commit (); // save account data share. edit (). putString ("usrPwd", userPass ). commit ();
Automatic Logon:
number.setText(userNum);pass.setText(userPass);        new NetWork().execute();

4. Switch the account. It is mainly used to clear the Stored Password and jump to the login interface.
/*** Switch account */public void change (View v) {share. edit (). clear (). commit (); // clear all data Intent intent = new Intent (); intent. setClass (NextActivity. this, MainActivity. class); startActivity (intent); this. finish ();}


Well, the above is the implementation of all functions. Of course, do not forget to add permissions in AndroidManifest for network programming. In addition, the above functions need to be used with the server for php development.

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.