Android login interface and function instance, android login interface
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. con Tent. 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 <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 logon 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); 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. v Iew. 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. imageVie W; 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 mLo GinLinearLayout; // The private LinearLayout mUserIdLinearLayout container for the login content; // The drop-down window displays private Animation mTranslate below this container; // The displacement Animation private Dialog mLoginingDlg; // display the currently logged-on Dialogprivate EditText mIdEditText; // 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. // the pop-up window is displayed. The buttons are private String mIdString and pr. Ivate String mPwdString; private ArrayList <User> mUsers; // User list private ListView mUserIdListView; // The ListView object private MyAapter mAdapter is displayed in the drop-down window; // ListView listener private PopupWindow mPop; // drop-down pop-up window @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_login); initView (); setListener (); mLoginLinearLayout. startAnimation (mTranslate );/ /Y-axis horizontal movement/* Get 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 (mUserI DListView); // it must be out of the parent-child relationship, otherwise mUserIdListView will be reported. setOnItemClickListener (this); // set the Click Event mAdapter = new MyAapter (mUsers); mUserIdListView. setAdapter (mAdapter);}/* ListView adapter */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) {convert View = 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. findViewById (R. id. login_delete_user); deleteUser. setOnClickListener (new OnClickListener () {// when you click Delete user euser, delete the selected element @ Overridepublic void onClick (View v) in mUsers) {If (getItem (position ). 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 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 sta Rt, 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); mPwdEditText = (EditText) findViewById (R. id. login_edtPwd); mMoreUser = (ImageView) findViewById (R. id. login_more_user); mLoginButton = (Button) findViewById (R. id. logi N_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); // initialize the animation object initLoginingDlg ();} public void initPop () {int width = mUserIdLinearLayout. getWidth ()-4; I Nt 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);}/* 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 (); // 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) g EtResources (). 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, so x, y indicates the offset of the control to the "screen center" */params. width = cxScreen; params. height = height; // width, height indicates the actual size of mLoginingDlg. setCanceledOnTouchOutside (true); // you can specify whether to click Dialog. Close Dialog}/* display 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.
In android programming, I want to provide a brief introduction to the first installation, but I will not be able to provide a brief introduction for the second installation, so I can directly log on to the interface,
There is no function description during installation. The installation process is controlled by the android system and will only read the permissions declared in your program ..
What do you mean is the first time you run the installation press?
In this case, you can save a sharePreference.
Read the file at startup. The introduction page is displayed if the file cannot be read for the first time. Then, save the sharePreference,
It won't be displayed in the future. It's easy.
How can I achieve automatic login on Android?
You can use SharedPreferences to store your account information or databases. The idea can be as follows: Write a Welcome interface, Judge in the onCreate method, and jump to the corresponding activity according to the conditions. For example, if no checked is set, start LoadActivity on the logon interface. If it is set, read the configuration information or the username and password stored in the database for automatic logon. After the verification is successful, the system will jump to the application function interface.