Android logon interface and function instances

Source: Internet
Author: User
Tags tojson

Android logon interface and function instances

Recently, an android applet needs to log on to the console. Now, you can take notes and learn from each other. Therefore, if you have any questions about my code, please submit them. Thank you!


The following describes the main content of this instance:

Enter the user name and password to read users from the local file userinfo. json. Determine whether the user name is in users. If not, add users. Every time you exit the Activity, use the AES algorithm to encrypt users and save it to userinfo. json. The User Name drop-down menu is implemented by PopupWindow + ListView.


Run:



Main Code:

1. User

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 "; // seed private static final String JSON_ID = "user_id"; private static final String JSON_PWD = "user_pwd"; private static final String TAG = "User "; public 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); // the decrypted data is stored in mId = AESUtils. decrypt (masterPassword, id); mPwd = AESUtils. decrypt (masterPassword, pwd) ;}public JSONObject toJSON () throws Exception {// save String id = AESUtils after encryption using the AES encryption algorithm. encrypt (masterPassword, mId); String pwd = AESUtils. encrypt (masterPassword, mPwd); Log. I (TAG, "encrypted:" + 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 "; // The user saves the file name private static final String TAG =" Utils ";/* saves the user logon information list */public static void saveUserList (Context context, ArrayList
 
  
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 logon information list */public static ArrayList
  
   
GetUserList (Context context) {/* load */FileInputStream in = null; ArrayList
   
    
Users = new ArrayList
    
     
(); 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); users. 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());byte[] 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(128, 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(raw, "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),16).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";private 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. widget. toast; public class LoginActivity extends Activity implements OnClickListener, OnItemClickListener, OnDismissListener {protected static final String TAG = "LoginActivity"; private LinearLayout listener; // The container for Logon content is private LinearLayout listener; // display the private Animation mTranslate; // The displacement Animation private Dialog mLoginingDlg; // display the Dialogprivate EditText mIdEditText being logged on; // The logon ID editing box is private EditText mPwdEditText. // The logon password editing box is private ImageView mMoreUser. // The drop-down icon is private Button mLoginButton. // The logon Button is private ImageView mLoginMoreUserView; // click the private String mIdString, private String mPwdString, and private ArrayList in the drop-down window.
 
  
MUsers; // user list private ListView mUserIdListView; // The ListView object private MyAapter mAdapter displayed in the drop-down window; // ListView listener private PopupWindow mPop; // drop-down window @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_login); initView (); setListener (); mLoginLinearLayout. startAnimation (mTranslate); // horizontal movement of the Y axis/* obtain the user password that has been saved */mUsers = Utils. getUserList (LoginActivity. this); if (mUsers. size ()> 0) {/* display the first user in the list in the editing 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); parent. removeView (mUserIdListView); // it must be out of the parent-child relationship. Otherwise, mUserIdListView is reported. setOnItemClickListener (this); // set the Click Event mAdapter = new MyAapter (mUsers); mUserIdListView. setAdapter (mAdapter);}/* ListView adapter */class MyAapter extends ArrayAdapter
  
   
{Public MyAapter (ArrayList
   
    
Users) {super (LoginActivity. this, 0, users);} public View getView (final int position, View convertView, ViewGroup parent) {if (convertView = null) {convertView = getLayoutInflater (). inflate (R. layout. listview_item, null);} TextView userIdText = (TextView) convertView. findViewById (R. id. listview_userid); userIdText. setText (getItem (position ). getId (); ImageView deleteUser = (ImageView) convertView. findView ById (R. id. login_delete_user); deleteUser. setOnClickListener (new OnClickListener () {// when you click Delete user euser, delete the selected element @ Overridepublic void onClick (View v) {if (getItem (position) in mUsers ). getId (). equals (mIdString) {// if the user Id to be deleted is the same as the current value in the Id editing box, the mIdString = ""; mPwdString = ""; mIdEditText. setText (mIdString); mPwdEditText. setText (mPwdString);} mUsers. remove (getItem (position); mAdapter. notifyDataSetChanged (); // update L IstView}); 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 () {pub Lic 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. setOnClickListener (this); mLoginMoreUserView. setOnClickListener (this);} private void initView () {mIdEditText = (EditText) findViewById (R. id. login_edtId); mPwdEditTe Xt = (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 = Anim AtionUtils. loadAnimation (this, R. anim. my_translate); // initialize the animation object initLoginingDlg ();} public void initPop () {int width = mUserIdLinearLayout. getWidth ()-4; int height = LayoutParams. WRAP_CONTENT; mPop = new PopupWindow (mUserIdListView, width, height, true); mPop. setOnDismissListener (this); // sets the listener when the pop-up window disappears. // note that this code should be added. Click other areas in the pop-up window to make the window disappear mPop. setBackgroundDrawable (new ColorDrawable (0 xffffffff);}/* initialization 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 (); // get the properties of the current window associated with mLoginingDlg to set the position it shows on the screen // get the screen's high width DisplayMetrics dm = new DisplayMetrics (); getWindowManager (). getdefadisplay display (). getMetrics (dm); int cxScreen = Dm. widthPixels; int cyScreen = dm. heightPixels; int height = (int) getResources (). getDimension (R. dimen. loginingdlg_height); // 42 dpint lrMargin = (int) getResources (). getDimension (R. dimen. loginingdlg_lr_margin); // left and right edges 10 dpint topMargin = (int) getResources (). getDimension (R. dimen. loginingdlg_top_margin); // the upper edge of 20dpparams. y = (-(cyScreen-height)/2) + topMargin; //-199/* the default position of the dialog box is in the center of the screen. Therefore, x and y indicate that Offset of "screen center" */params. width = cxScreen; params. height = height; // width, height indicates the actual size of mLoginingDlg. setCanceledOnTouchOutside (true); // you can click any external area of Dialog to close the Dialog}/* display the logon Dialog box */private void showLoginingDlg () {if (mLoginingDlg! = Null) mLoginingDlg. show ();}/* close the Login 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 to log on to showLoginingDlg (); // display the "logging in" dialog box. Because this Demo is not logged on to the web server, the effect may not be displayed. you can use Log. I (TAG, mIdString + "" + mPwdString); if (mIdString = null | mIdString. equals ("") {// Toast when the account is empty. makeText (LoginActivity. this, "enter your account", Toast. LENGTH_SHORT ). show ();} else if (m PwdString = null | mPwdString. equals ("") {// when the password is null, Toast. makeText (LoginActivity. this, "enter the password", Toast. LENGTH_SHORT ). show ();} When else {// account and password are not empty, boolean mIsSave = true; try {Log. I (TAG, "Save User List"); for (user: mUsers) {// determine whether the local document has this ID User if (user. getId (). equals (mIdString) {mIsSave = false; break ;}} if (mIsSave) {// Add a new user to usersUser User = new user (mIdString, mPwdString); mUsers. add (user) ;}} catch (E Xception e) {e. printStackTrace ();} closeLoginingDlg (); // close the dialog box Toast. makeText (this, "Logon successful", Toast. LENGTH_SHORT ). show (); finish ();} break; case R. id. login_more_user: // if (mPop = null) {initPop ();} if (! MPop. isShowing () & mUsers. size ()> 0) {// Log. I (TAG, "switch to badge"); mMoreUser. setImageResource (R. drawable. login_more_down); // switch the mPop icon. showAsDropDown (mUserIdLinearLayout, 2, 1); // display the 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 ();}/* events when the PopupWindow object dismiss */@ Overridepublic void onDismiss () {// Log. I (TAG, "switch to badge"); mMoreUser. setImageResource (R. drawable. login_more_up);}/* save users */@ Overridepublic void onPause () {super. onPause (); try {Utils. saveUserList (LoginActivity. this, mUsers);} catch (Exception e) {e. printStackTrace ();}}}
   
  
 


I will not list other la S and resource configurations in detail. For more information, see the source code.


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.