This project is written in eclipse software. Through my own practice, it is true and effective. I hope it can help you.😘😘 Project Version: Android 5.1.1 ADT version: 23.0.6 SDK Version: 24.4.1 Run simulator: Night God simulator If there are any shortcomings or inappropriate places, you're welcome to be pointed out by the big guys |
Source download link for this project:
https://download.csdn.net/download/hyh17808770899/20285938
Download the apk installation to see how it works before downloading the source code: https://yuyunyaohui.lanzoui.com/ipirYrf1byd
Adding picture authentication codes during login can prevent malicious decryption of the codes, effectively prevent a hacker from continuously attempting to log on to a specific registered user by using specific program violence, and increase the security of login.
In the login interface, a picture verification code is implemented through an EditText text input box and an ImageView control, where EditText is used to enter the verification code and ImageView is used to display the verification code.When you click Login, if the username and password are correct, you can start to judge if the verification code is entered correctly and enter correctly to enter the home page.You can also click on the picture of the verification code to refresh the verification code.
1. Activity_in the layout folder under the res directoryAdd code to login.xml
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="35dp" android:layout_marginRight="35dp" android:layout_marginTop="20dp" android:orientation="horizontal" > <LinearLayout android:layout_width="wrap_content" android:layout_height="40dp" android:background="@drawable/linearlayout" > <EditText android:id="@+id/et_phoneCodes" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:background="@null" android:textColor="#000000" android:textColorHint="#a3a3a3" android:hint="Please enter the right verification code" /> </LinearLayout> <ImageView android:id="@+id/iv_showCode" android:layout_width="100dp" android:layout_marginLeft="10dp" android:layout_height="match_parent" /> </LinearLayout>
After adding the above code, the interface looks like this:
2. Add Authentication Code Input Box Style
Create a new linearlayout.xml file in the drawable folder under the res directory
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#ffffff" /> <stroke android:width="0.5dip" android:color="#ed6d48" /> <corners android:radius="15dp"/> </shape>
3. Authentication code generation logic code
Create a new china.ynyx.heyunhui.yanzhengma package under res, in which a new Code.java file is created
You can remove low-recognition English letters, such as big Z and small Z
package china.ynyx.heyunhui.yanzhengma; import java.util.Random; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Bitmap.Config; public class Code { private static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private static Code bmpCode; public static Code getInstance() { if(bmpCode == null) bmpCode = new Code(); return bmpCode; } //default settings private static final int DEFAULT_CODE_LENGTH = 4; private static final int DEFAULT_FONT_SIZE = 25; private static final int DEFAULT_LINE_NUMBER = 2; private static final int BASE_PADDING_LEFT = 10, RANGE_PADDING_LEFT = 15, BASE_PADDING_TOP = 15, RANGE_PADDING_TOP = 20; private static final int DEFAULT_WIDTH = 100, DEFAULT_HEIGHT = 40; //settings decided by the layout xml //canvas width and height private int width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT; //random word space and pading_top private int base_padding_left = BASE_PADDING_LEFT, range_padding_left = RANGE_PADDING_LEFT, base_padding_top = BASE_PADDING_TOP, range_padding_top = RANGE_PADDING_TOP; //number of chars, lines; font size private int codeLength = DEFAULT_CODE_LENGTH, line_number = DEFAULT_LINE_NUMBER, font_size = DEFAULT_FONT_SIZE; //variables private String code; private int padding_left, padding_top; private Random random = new Random(); //Authentication Code Picture public Bitmap createBitmap() { padding_left = 0; Bitmap bp = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas c = new Canvas(bp); code = createCode(); c.drawColor(Color.WHITE); Paint paint = new Paint(); paint.setTextSize(font_size); for (int i = 0; i < code.length(); i++) { randomTextStyle(paint); randomPadding(); c.drawText(code.charAt(i) + "", padding_left, padding_top, paint); } for (int i = 0; i < line_number; i++) { drawLine(c, paint); } c.save( Canvas.ALL_SAVE_FLAG );//Preservation c.restore();// return bp; } public String getCode() { return code; } //Verification Code private String createCode() { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < codeLength; i++) { buffer.append(CHARS[random.nextInt(CHARS.length)]); } return buffer.toString(); } private void drawLine(Canvas canvas, Paint paint) { int color = randomColor(); int startX = random.nextInt(width); int startY = random.nextInt(height); int stopX = random.nextInt(width); int stopY = random.nextInt(height); paint.setStrokeWidth(1); paint.setColor(color); canvas.drawLine(startX, startY, stopX, stopY, paint); } private int randomColor() { return randomColor(1); } private int randomColor(int rate) { int red = random.nextInt(256) / rate; int green = random.nextInt(256) / rate; int blue = random.nextInt(256) / rate; return Color.rgb(red, green, blue); } private void randomTextStyle(Paint paint) { int color = randomColor(); paint.setColor(color); paint.setFakeBoldText(random.nextBoolean()); //true is bold, false is non-bold float skewX = random.nextInt(11) / 10; skewX = random.nextBoolean() ? skewX : -skewX; paint.setTextSkewX(skewX); //float type parameter, negative number means right diagonal, integer left diagonal // paint.setUnderlineText(true); //true is underlined, false is not underlined // paint.setStrikeThruText(true); //true is a strikethrough, false is a non-strikethrough } private void randomPadding() { padding_left += base_padding_left + random.nextInt(range_padding_left); padding_top = base_padding_top + random.nextInt(range_padding_top); } }
3. Random Authentication Code Implementation Code
Add logic code to the LoginActivity.java file in the china.ynyx.heyunhui.activity package
Definition:
//Verification Code private ImageView iv_showCode; private EditText et_phoneCode; //Generated Authentication Code private String realCode;
Add in the init() method:
//Verification Code et_phoneCode = (EditText) findViewById(R.id.et_phoneCodes); iv_showCode = (ImageView) findViewById(R.id.iv_showCode);
Add Authentication Code Display Method as Picture
//Verification Code private void reacode() { //Show the verification code as a picture iv_showCode.setImageBitmap(Code.getInstance().createBitmap()); realCode = Code.getInstance().getCode(); }
Call method: Add in the onCreate(Bundle savedInstanceState) method:
reacode();
4. Picture Verification Code Click Refresh
Listen event to add a captcha picture in the init() method
//Picture Authentication Code Refresh iv_showCode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub iv_showCode.setImageBitmap(Code.getInstance().createBitmap()); realCode = Code.getInstance().getCode(); } });
5. Wrong Verification Code Judgment
Get the user-entered authentication code in the Authentication Code input box after the username password is correct
String phoneCode = et_phoneCode.getText().toString();
Compare it to the verification code generated in the picture
phoneCode.equals(realCode)
If the same, the login succeeds, but not the same, the login fails
Toast.makeText(LoginActivity.this, phoneCode+"Authentication code error", Toast.LENGTH_SHORT).show();
Okay, so the picture verification code function is implemented, the demonstration effect is at the beginning of the article, and then the login function logic complete code is pasted (login button logic code has been greatly modified by me, please compare carefully):
package china.ynyx.heyunhui.activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import china.ynyx.heyunhui.MainActivity; import china.ynyx.heyunhui.R; import china.ynyx.heyunhui.utils.MD5Utils; import china.ynyx.heyunhui.yanzhengma.Code; import china.ynyx.heyunhui.activity.LoginActivity; import china.ynyx.heyunhui.activity.FindPswActivity; public class LoginActivity extends AppCompatActivity{ private TextView tv_main_title;//Title private TextView tv_back; //Return button private TextView tv_register,tv_find_pwd;//Control to register and retrieve password immediately private Button btn_login; //Logon button private EditText et_user_name,et_pwd;//User name, password control private String username,pwd,spPwd;//Get value of user name, password control /*Code to Complete Portrait Modification Function - Innovation Function One*/ public ImageView iv_head = null; private static String path = "/sdcard/DemoHead/";//sd Path /*Code to Complete Portrait Modification Function - Innovation Function One*/ //Verification Code private ImageView iv_showCode; private EditText et_phoneCode; //Generated Authentication Code private String realCode; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //Set this interface as a vertical screen setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); init(); //Verification Code reacode(); /*Code to Complete Portrait Modification Function - Innovation Function One*/ Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");//From Sd to Bitmap iv_head = (ImageView)findViewById(R.id.iv_head); if(bt!=null){ iv_head.setImageBitmap(bt); }else{ /** * If there is no SD in it, you need to take the avatar from the server, take it back and save it in SD */ iv_head.setImageResource(R.drawable.default_icon); } /*Code to Complete Portrait Modification Function - Innovation Function One*/ } //Verification Code private void reacode() { //Show the verification code as a picture iv_showCode.setImageBitmap(Code.getInstance().createBitmap()); realCode = Code.getInstance().getCode(); } private void init() { // TODO Auto-generated method stub tv_main_title=(TextView)findViewById(R.id.tv_main_title); tv_main_title.setText("Sign in"); tv_back = ((TextView) findViewById(R.id.tv_back)); tv_register = (TextView) findViewById(R.id.tv_register); tv_find_pwd = (TextView) findViewById(R.id.tv_find_pwd); btn_login = (Button) findViewById(R.id.btn_login); et_user_name = (EditText) findViewById(R.id.et_user_name); et_pwd = (EditText) findViewById(R.id.et_pwd); //Verification Code et_phoneCode = (EditText) findViewById(R.id.et_phoneCodes); iv_showCode = (ImageView) findViewById(R.id.iv_showCode); //Picture Authentication Code Refresh iv_showCode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub iv_showCode.setImageBitmap(Code.getInstance().createBitmap()); realCode = Code.getInstance().getCode(); } }); //Return button click event tv_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub LoginActivity.this.finish(); } }); //Register the control's click event now tv_register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent=new Intent(LoginActivity.this,RegisterActivity.class); startActivityForResult(intent, 1); } }); //Retrieve Password Click Event tv_find_pwd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub //Jump to the Retrieve Password interface (which has not been created yet) Intent intent=new Intent(LoginActivity.this,FindPswActivity.class); startActivityForResult(intent, 1); } }); //Logon Button Click Event btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub username=et_user_name.getText().toString().trim(); pwd=et_pwd.getText().toString().trim(); String md5Pwd=MD5Utils.MD5(pwd); spPwd=readPwd(username); if(TextUtils.isEmpty(username)){ Toast.makeText(LoginActivity.this, "enter one user name", Toast.LENGTH_SHORT).show(); return; }else if (TextUtils.isEmpty(pwd)){ Toast.makeText(LoginActivity.this, "Please input a password", Toast.LENGTH_SHORT).show(); return; }else if(md5Pwd.equals(spPwd)){ String phoneCode = et_phoneCode.getText().toString(); if(phoneCode.equals(realCode)){ Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_SHORT).show(); //Save login status and login user name in SharedPreferences saveLoginStatus(true,username); //After successful login, pass the status of successful login to MainActivity.java via Intent Intent data=new Intent(); data.putExtra("isLogin",true); setResult(RESULT_OK,data);//setResult is OK, close the current page LoginActivity.this.finish();//At the time of login, register if the user has not already registered.Return the successful user name to the previous page after successful registration startActivity(new Intent(LoginActivity.this, MainActivity.class)); }else{ Toast.makeText(LoginActivity.this, phoneCode+"Authentication code error", Toast.LENGTH_SHORT).show(); } return; }else if((!TextUtils.isEmpty(spPwd)&&!md5Pwd.equals(spPwd))){ Toast.makeText(LoginActivity.this, "ERROR Incorrect username or password", Toast.LENGTH_SHORT).show(); return; }else { Toast.makeText(LoginActivity.this, "This user does not exist", Toast.LENGTH_SHORT).show(); } } }); } //Read password from SharedPreferences based on user name private String readPwd(String username){ SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE); return sp.getString(username,""); } //Save login status and login username to SharedPrefarences private void saveLoginStatus(boolean status,String username){ //loginInfo denotes the file name SharedPreferences sp=getSharedPreferences("loginInfo", MODE_PRIVATE); SharedPreferences.Editor editor=sp.edit();//Get Editor editor.putBoolean("isLogin", status); editor.putString("loginUserName", username);//Save user name at logon editor.commit();//Submit modifications } @Override protected void onActivityResult(int requestCode,int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if(data!=null){ //User name passed in from the registration interface String username=data.getStringExtra("username"); if(!TextUtils.isEmpty(username)){ et_user_name.setText(username); //Set cursor position et_user_name.setSelection(username.length()); } } } }
eclipse-based Android Project Actual - Savvy Valley (zero) Create and run Android projects
eclipse-based android project practice-savvy (1) welcome interface
eclipse-based android project practice-savvy (2) registration interface
eclipse-based android project practice-savvy (3) login interface
Actual Operations for android Project based on eclipse-Bosch Valley (IV) Bottom Navigation Bar
eclipse-based android project practice-savvy (5) "me" module
eclipse-based android project practice-knowledgeable Valley (6) setting interface
Actual Operations for android Project based on eclipse - Educational Valley (7) Modify Password
android Project Actual Warfare based on eclipse - Educational Valley (8) Setting Secret Security and Retrieving Passwords
eclipse-based android project reality-savvy (9) profile interface
eclipse-based android Project Actual Warfare-Educational Valley (10) Personal Data Modification
eclipse-based android project practice-savvy (11) exercise interface
eclipse-based android project practice-savvy (12) exercise details interface
eclipse-based android project practice-Bosch Valley (13) horizontal sliding ad bar interface
eclipse-based android project practice-knowledgeable Valley (14) course interface
eclipse-based android project practice-savvy (fifteen) course details interface
eclipse-based android project reality-savvy (sixteen) video playback interface
eclipse-based android project reality-savvy (17) playback record interface
eclipse-based android Project Actual Warfare - Savvy Valley (18) Play different videos (web videos)
eclipse-based android Project Actual Warfare - Savvy Valley (19) Play different videos (local videos)
Actual Operations for android Project based on eclipse - Bosch Valley (20) HCIA-Kunpeng
eclipse-based android Project Actual Warfare-Bosch Valley (21) android Replacement Avatar feature (available in live android 9 and below)