Recently an Android applet requires login function, I simply implemented a bit. Now it is recorded as a note, and I hope to learn from each other. So, if there is a problem with my code, please ask. Thank you so much!
The following is a brief summary of the main contents of this example:
Enter the user name and password to read users from the local file Userinfo.json . Determine if this user name is in users, and if not, join users, each time you exit Activity , encrypt users with the AES algorithm and then save to Userinfo.json. The user Name drop-down menu is implemented by the Popupwindow + ListView .
Run:
The main code:
1. User Class
Package Com.example.logindemo;import Org.json.jsonexception;import Org.json.jsonobject;import android.util.Log; public class User {private string Mid;private string mpwd;private static final String Masterpassword = "foryou";//AES Encryption calculation The seed of the FA private static final string json_id = "user_id";p rivate static final String json_pwd = "User_pwd";p rivate static final String TAG = "User";p ublic user (string ID, string pwd) {This.mid = Id;this.mpwd = pwd;} Public User (Jsonobject json) throws Exception {if (Json.has (json_id)) {String ID = json.getstring (json_id); String pwd = json.getstring (JSON_PWD);//decrypt to store mid = Aesutils.decrypt (Masterpassword, id); mpwd = Aesutils.decrypt ( Masterpassword, PWD);}} Public Jsonobject ToJSON () throws Exception {//save string id = Aesutils.encrypt (masterpassword, MId) after encrypting with AES encryption algorithm; String pwd = Aesutils.encrypt (Masterpassword, mpwd); LOG.I (TAG, "after encryption:" + ID + "" + pwd); Jsonobject json = new Jsonobject (); try {json.put (json_id, ID); Json.put (Json_pwd, PWD);} catch (Jsonexception e) {E.printstacktrace ();} return JSON;} Public String GetId () {return mId;} Public String getpwd () {return mpwd;}}
2. Save and load the local user list
Package Com.example.logindemo;import Java.io.bufferedreader;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.outputstreamwriter;import Java.io.writer;import Java.util.ArrayList;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsontokener;import Android.content.Context; Import Android.util.log;public class Utils {private static final String filename = "Userinfo.json";//user save file name Private stat IC final String TAG = "Utils";/* Save user login information list */public static void Saveuserlist (context context, arraylist<user> users ) throws Exception {/* Save */log.i (TAG, "saving"); Writer writer = Null;outputstream out = null; Jsonarray array = new Jsonarray (); for (User user:users) {array.put (User.tojson ());} try {out = Context.openfileoutput (FILENAME, context.mode_private);//overwrite writer = new OutputStreamWriter (out); LOG.I (TAG, "JSON value:" + array.tostring ()); Writer.write (arrAy.tostring ());} finally {if (writer! = null) Writer.close ();}} /* Get user login Information list */public static arraylist<user> Getuserlist (context context) {/* load */fileinputstream in = null; arraylist<user> users = new arraylist<user> (); try {in = Context.openfileinput (FILENAME); BufferedReader reader = new BufferedReader (new InputStreamReader (in)); StringBuilder jsonstring = new StringBuilder (); Jsonarray Jsonarray = new Jsonarray (); String Line;while (line = Reader.readline ())! = null) {jsonstring.append (line);} LOG.I (TAG, jsonstring.tostring ()); Jsonarray = (Jsonarray) New Jsontokener (Jsonstring.tostring ()). NextValue (); Converts a string to a Jsonarray object for (int i = 0; i < jsonarray.length (); i++) {User user = new User (Jsonarray.getjsonobject (i)); Rs.add (user);}} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} catch ( Jsonexception e) {e.printstacktrace ();} catch (Exception e) {e.printstacktrace ();} return users;}}
3. AES Encryption/decryption
Package Com.example.logindemo;import Java.security.securerandom;import Javax.crypto.cipher;import Javax.crypto.keygenerator;import Javax.crypto.secretkey;import Javax.crypto.spec.ivparameterspec;import Javax.crypto.spec.secretkeyspec;public class Aesutils {public static string encrypt (string seed, String cleartext) Throws Exception {byte[] Rawkey = Getrawkey (Seed.getbytes ()); byte[] result = Encrypt (Rawkey, cleartext.getbytes ()); return Tohex (result);} public static string decrypt (string seed, string encrypted) throws Exception {byte[] Rawkey = Getrawkey (Seed.getbytes ()); b yte[] enc = tobyte (encrypted); byte[] result = Decrypt (rawkey, ENC); return new String (result); private static byte[] Getrawkey (byte[] seed) throws Exception {Keygenerator KGen = keygenerator.getinstance ("AES"); securerandom sr = securerandom.getinstance ("Sha1prng", "Crypto"); Sr.setseed (seed); Kgen.init (SR); Secretkey skey = Kgen.generatekey (); byte[] raw = skey.getencoded (); return raw;} private static byte[] Encrypt (byte[]Raw, byte[] clear) throws Exception {Secretkeyspec Skeyspec = new Secretkeyspec (Raw, "AES"); Cipher Cipher = cipher.getinstance ("AES"); Cipher.init (Cipher.encrypt_mode, Skeyspec, New Ivparameterspec (New byte[ Cipher.getblocksize ()]); byte[] encrypted = cipher.dofinal (clear); return encrypted;} private static byte[] Decrypt (byte[] raw, byte[] encrypted) throws Exception {Secretkeyspec Skeyspec = new Secretkeyspec (RA W, "AES"); Cipher Cipher = cipher.getinstance ("AES"); Cipher.init (Cipher.decrypt_mode, Skeyspec, New Ivparameterspec (New byte[ Cipher.getblocksize ()])); byte[] decrypted = cipher.dofinal (encrypted); return decrypted;} private static string Tohex (String txt) {return Tohex (Txt.getbytes ());} private static string Fromhex (String hex) {return new string (ToByte (hex));} private static byte[] ToByte (String hexstring) {int len = hexstring.length ()/2;byte[] result = new Byte[len];for (int i = 0; i < Len; i++) Result[i] = integer.valueof (hexstring.substring (2 * I, 2 * i + 2), +). Bytevalue (); return result; private static String Tohex (byte[] buf) {if (buf = = null) return ""; StringBuffer result = new StringBuffer (2 * buf.length); for (int i = 0; i < buf.length; i++) {Appendhex (result, buf[i]); }return result.tostring ();} Private final static String hex = "0123456789ABCDEF";p rivate static void Appendhex (StringBuffer sb, byte b) {Sb.append (HEX . CharAt ((b >> 4) & 0x0f). Append (Hex.charat (b & 0x0f));}}
4, Loginactivity.java
Package Com.example.logindemo;import Java.util.arraylist;import Android.app.activity;import android.app.Dialog; Import Android.graphics.drawable.colordrawable;import Android.os.bundle;import Android.text.editable;import Android.text.textwatcher;import Android.util.displaymetrics;import Android.util.log;import Android.view.View; Import Android.view.viewgroup;import Android.view.window;import Android.view.windowmanager;import Android.view.view.onclicklistener;import Android.view.viewgroup.layoutparams;import Android.view.animation.animation;import Android.view.animation.animationutils;import Android.widget.AdapterView; Import Android.widget.adapterview.onitemclicklistener;import Android.widget.arrayadapter;import Android.widget.button;import Android.widget.edittext;import Android.widget.imageview;import Android.widget.linearlayout;import Android.widget.listview;import Android.widget.popupwindow;import Android.widget.popupwindow.ondismisslistener;import Android.widget.textview;import Android. Widgets. Toast;public class Loginactivity extends Activity implements Onclicklistener,onitemclicklistener, Ondismisslistener { Protected static final String TAG = "loginactivity";p rivate linearlayout mloginlinearlayout; Login contents of the container private linearlayout museridlinearlayout; The drop-down pop-up window displays the private Animation mtranslate below this container; Displacement animation private Dialog Mloginingdlg; Displays the Dialogprivate EditText midedittext that is being logged in; Login ID edit box private EditText mpwdedittext; Login password edit box private ImageView mmoreuser; Drop-down icon private Button Mloginbutton; Login button private ImageView mloginmoreuserview; Pop-down Popup button private string Midstring;private string mpwdstring;private arraylist<user> musers; User list private ListView museridlistview; The drop-down pop-up window displays the ListView object Private Myaapter Madapter; ListView Listener Private Popupwindow MPop; Drop-down popup @overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_login); Initview (); Setlistener (); Mloginlinearlayout.startanimation (mTranslATE); Y-Axis Horizontal movement/* Gets the saved user password */musers = utils.getuserlist (loginactivity.this); if (musers.size () > 0) {/* The first user in the list is displayed in the edit box */midedittext.settext (Musers.get (0). GetId ()); Mpwdedittext.settext (Musers.get (0). GETPWD ());} LinearLayout parent = (linearlayout) getlayoutinflater (). Inflate (R.layout.userifo_listview, null); Museridlistview = ( ListView) Parent.findviewbyid (Android. r.id.list);p Arent.removeview (Museridlistview); Must be divorced from the parent-child relationship, or will error Museridlistview.setonitemclicklistener (this); Set Click things madapter = new Myaapter (musers); Museridlistview.setadapter (Madapter);} /* The adapter for the ListView */class Myaapter extends arrayadapter<user> {public myaapter (arraylist<user> users) {super ( Loginactivity.this, 0, users);} Public View GetView (final int position, View Convertview,viewgroup parent) {if (Convertview = = null) {Convertview = Getlay Outinflater (). Inflate (R.layout.listview_item, null);} TextView Useridtext = (TextView) Convertview.findviewbyid (R.id.listview_userid); Useridtext.settext (GetItem (positION). GetId ()); ImageView deleteuser = (ImageView) Convertview.findviewbyid (R.id.login_delete_user); Deleteuser.setonclicklistener (New Onclicklistener () {//click Delete DeleteUser in Musers to delete the selected element @overridepublic void OnClick (View v) {if (GetItem (position). GetId () equals (midstring)) {//If the current value of the user ID and ID edit box to be deleted is equal, then empty midstring = ""; mpwdstring = ""; Midedittext.settext (midstring); Mpwdedittext.settext (mpwdstring);} Musers.remove (GetItem (position)); madapter.notifydatasetchanged (); Update ListView}}); return convertview;}} private void Setlistener () {Midedittext.addtextchangedlistener (new Textwatcher () {public void ontextchanged ( charsequence s, int start, int before,int count) {midstring = S.tostring ();} public void beforetextchanged (Charsequence s, int. start, int count,int after) {}public void aftertextchanged (Editable s) { }}); Mpwdedittext.addtextchangedlistener (new Textwatcher () {public void ontextchanged (charsequence s, int start, int Before,int count) {mpwdstring = S.tostring ();} public void beforetextchanged (Charsequence s, int start, int count,int after) {}public void aftertextchanged (Editable s) {}}); Mloginbutton.setonclicklis Tener (this); Mloginmoreuserview.setonclicklistener (this);} private void Initview () {midedittext = (EditText) Findviewbyid (r.id.login_edtid); mpwdedittext = (EditText) Findviewbyid (r.id.login_edtpwd); mmoreuser = (ImageView) Findviewbyid (r.id.login_more_user); Mloginbutton = (Button) Findviewbyid ( R.id.login_btnlogin); Mloginmoreuserview = (ImageView) Findviewbyid (r.id.login_more_user); mloginlinearlayout = ( LinearLayout) Findviewbyid (r.id.login_linearlayout); museridlinearlayout = (linearlayout) findViewById (R.id.userId_ LinearLayout); mtranslate = Animationutils.loadanimation (this, r.anim.my_translate); Initializes the animated object Initloginingdlg ();} public void Initpop () {int width = museridlinearlayout.getwidth ()-4;int height = Layoutparams.wrap_content;mpop = new Po Pupwindow (Museridlistview, width, height, true), Mpop.setondismisslistener (this),///Set pop-up window disappears listener//Note To add this code, Click the pop-up window to make the window disappear. MPOP.setbackgrounddrawable (New colordrawable (0xFFFFFFFF));} /* Initialize the login dialog box */private void Initloginingdlg () {Mloginingdlg = new Dialog (this, r.style.loginingdlg); Mloginingdlg.setcontentview (R.LAYOUT.LOGINING_DLG); window window = Mloginingdlg.getwindow (); Windowmanager.layoutparams params = window.getattributes ();//Gets and Mloginingdlg the properties of the current window associated with it, setting the position it appears on the screen// Gets the screen's high-width displaymetrics dm = new Displaymetrics (); Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM); int cxscreen = Dm.widthpixels;int Cyscreen = dm.heightpixels;int height = (int) getresources (). Getdimension (R.dimen.loginingdlg_ height);//High 42dpint lrmargin = (int) getresources (). Getdimension (R.dimen.loginingdlg_lr_margin); Left and right edge 10dpint topMargin = (int) getresources (). Getdimension (R.dimen.loginingdlg_top_margin); Upper Edge 20dpparams.y = (-(cyscreen-height)/2) + TopMargin; The -199/* dialog box default location is in the center of the screen, so X, Y represents the offset of this control to the screen center */params.width = cxscreen;params.height = height;//width, The height represents the actual size of the Mloginingdlg Mloginingdlg.setcanceledontouchoutsidE (true); Set Click Dialog outside any area close dialog}/* display the login dialog box */private void Showloginingdlg () {if (Mloginingdlg! = null) mloginingdlg.show () ;} /* Close the logon dialog box */private void Closeloginingdlg () {if (Mloginingdlg! = null && mloginingdlg.isshowing ()) Mloginingdlg.dismiss ();} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case r.id.login_btnlogin://start login Showloginingdlg ();//display "Logging in" dialog box because this demo does not log on to the Web server, so the effect may not be visible. Can be combined with log.i (TAG, midstring + "" + mpwdstring), if (midstring = = NULL | | Midstring.equals ("")) {//account is empty toast.maketext (loginactivity.this, "Please enter account", Toast.length_short). Show (); else if (mpwdstring = = NULL | | mpwdstring.equals ("")) {//password is empty toast.maketext (loginactivity.this, "Please enter password", Toast.length_ Short). Show ();} else {//account and password are NOT NULL when Boolean missave = true;try {log.i (TAG, "Save user List"), for (user user:musers) {///To determine if the local document has this ID user if (user.g Etid (). Equals (midstring)) {missave = False;break;}} if (missave) {//Add new user to Usersuser username = new Subscriber (midstring, mpwdstring); Musers.add (user);}} CaTCH (Exception e) {e.printstacktrace ();} Closeloginingdlg ();//Close the dialog box Toast.maketext (this, "Login successful", Toast.length_short). Show (); Finish ();} Break;case R.id.login_more_user://When clicking on the drop-down bar if (MPop = = null) {Initpop ();} if (!mpop.isshowing () && musers.size () > 0) {//LOG.I (TAG, "Switch to angular label"); Mmoreuser.setimageresource ( R.drawable.login_more_down); Toggle Icon Mpop.showasdropdown (museridlinearlayout, 2, 1); Show pop-up Window}break;default:break;}} @Overridepublic void Onitemclick (adapterview<?> parent, view view, int Position,long id) {Midedittext.settext ( Musers.get (position). GetId ()) Mpwdedittext.settext (Musers.get (position). GETPWD ()); Mpop.dismiss (); /* Popupwindow Object Dismiss event */@Overridepublic void Ondismiss () {//LOG.I (TAG, "Switch to angular label"); Mmoreuser.setimageresource ( R.DRAWABLE.LOGIN_MORE_UP);} /* Save users */@Overridepublic void OnPause () {super.onpause () when exiting this activity, try {utils.saveuserlist (loginactivity.this, Musers);} catch (Exception e) {e.printstacktrace ();}}}
some other layout and resource configuration I will not be listed in detail, want to see can download Source Code
Android implements login interface and feature instances