Android gesture Password

Source: Internet
Author: User
<span id="Label3"></p><p><p>Recently saw Mu class nets a teacher's video, about the gesture password research, very good, but did not upload the source code, There is the calculation of the rotation angle of the individual feeling is not very good, so the source codes are as Follows:</p></p><p><p></p></p><pre name="code" class="java">Import Java.util.arraylist;import java.util.list;import Mg.lanyan.ui.r;import android.annotation.SuppressLint; Import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.matrix;import Android.graphics.paint;import Android.util.attributeset;import android.view.motionevent;import android.view.View; @SuppressLint ({" Drawallocation "," clickableviewaccessibility "}) public class Lockpaternview extends View{public boolean isontouch= false;private int mscreenwidth;private int mscreenheight;/** Nine Gongge points collection */private point [] pointarray=new point[3][3];/** Avoid initializing points every time */private the offset of the boolean isfirst;/**x axis */private The offset of the float offsetx;/**y axis */private float offsety;/** The required picture resources id*/ private int normal=r.drawable.nor,press=r.drawable.press,error=r.drawable.error,linepress=r.drawable.linepress, lineerror=r.drawable.lineerror;/** the picture bitmap*/private Bitmap Mbitmapnormal,mbitmappress,mbitmaperror from the resource id, Mbitmaplinepress,mbitmaplineerror;/** Draw pattern Brush */private paint mpaint=new Paint (paint.anti_alias_flag); * * Pattern radius */private int mradior;/** Store pressed point collection */private list<point> pointlist=new arraylist<point> ();p rivate Float mcurrx,mcurry;/** whether to choose */private Boolean isselect;/** whether to continue drawing */private Boolean ismovepoint;/** whether to end */private Boolean isfinished;/** matrix for scaling measurements */private matrix matrix=new matrix ();p rivate int status_password=0;private int Status_ password_ok=0;private int status_password_error=1;public lockpaternview (context context, attributeset attrs, int Defstyleattr) {super (context, attrs, Defstyleattr);//TODO auto-generated constructor stub}public Lockpaternview ( Context context, AttributeSet attrs) {this (context, Attrs,0);//TODO auto-generated Constructor stub}public Lockpaternview (context Context) {this (context,null);//TODO auto-generated constructor stub} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//TODO auto-generated method Stubsuper.onmeasure ( widthmeasurespec, Heightmeasurespec);} @Overridepublic boolean ontouchevent (motionevent event) {//TODO auto-generated method stubisontouch=true;ismovepoint= False;isfinished=false;int action=event.getaction (); mcurrx=event.getx (); mcurry=event.gety (); Point Mpointintersection=null;switch (action) {case MotionEvent.ACTION_DOWN:resetPointList (); mpointintersection= CheckPoint (); if (mpointintersection!=null) {isselect=true;} Break;case MotionEvent.ACTION_MOVE:if (isselect) {mpointintersection=checkpoint (); if (mpointintersection==null) { ismovepoint=true;}} Break;case motionevent.action_up:isfinished=true;isselect=false;isontouch=false;break;default:break;} Gesture does not end if (!isfinished&&isselect&&mpointintersection!=null) {if (crosspoint (MPOINTINTERSECTION)) {ismovepoint=true;} Else{mpointintersection.status=point.statu_press;pointlist.add (mpointintersection);}} Gesture End If (isfinished) {if (pointlist.size () <=4&&pointlist.size () >=2) {//draw error Errorpoint (); status_password=status_password_error;} else if (pointlist.size () <=1) {resetpointlist ();//draw not set}else{status_password=status_password_ok;}} Postinvalidate (); If (isfinished&&listener!=null) {if (status_password==status_password_error) { Listener.onfail ();} else if (status_password==status_password_ok) {String mpassword=getpassword (); listener.onsucceed (mpassword);}} Return true;} @Overrideprotected void OnDraw (canvas canvas) {//TODO auto-generated method Stubsuper.ondraw (canvas), if (!isfirst) { Initpoint ();} Pointtocanvas (canvas), if (pointlist.size () >0) {point a=pointlist.get (0), for (int i = 0; i < pointlist.size (); I++) { Point B=pointlist.get (i); linetocanvas (canvas, a, b); a=b;} If (ismovepoint) {linetocanvas (canvas, a, New Point (mcurrx,mcurry));}}} /*************************************method****************************************//** * Ask for the angle between two points * @param px1 * @ Param py1 * @param px2 * @param py2 * @return */public static float getangle (float px1, float py1, float px2, float Py2) { Two point x, y value float x = px2-px1; Float y = py2-py1; Double hypotenuse = Math.sqrt (math.pow (x, 2) + math.pow (y, 2)); hypotenuse length double cos = x/hypotenuse; Double radian = Math.acos (cos); Find the radian float angle = (float) (math.pi/radian); Calculate the angle in radians if (y < 0) {angle = + + (180-angle); } else if ((y = = 0) && (x < 0)) {angle = 180; }else if (x==0&&y==0) {angle=0;} Return angle; }/** * Draw Line * @param canvas * @param A * @param b */public void Linetocanvas (canvas canvas,point a,point b) {float scalex= (float) getdistance (a, b)/mbitmaplinepress.getwidth (), float mangle=getangle (a.x, a.y, b.x, b.y); canvas.rotate (mAngle , a.x,a.y), if (a.status==point.statu_press) {matrix.setscale (scaleX, 1); matrix.posttranslate ( A.x-mbitmaplinepress.getwidth ()/2, a.y-mbitmaplinepress.getheight ()/2);//offset canvas.drawbitmap (mBitmapLinePress, matrix, mpaint);} Else{matrix.setscale (scaleX, 1); matrix.posttranslate (a.x-mbitmaplineerror.getwidth ()/2, A.y-mbitmaplineerror.getheight ()/2);//offset canvas.drawbitmap (mbitmaplineerror, matrix, mpaint);} Canvas.rOtate (-mangle,a.x,a.y);} /** * To determine if it is an intersection * @param point * @return */public boolean crosspoint (points) {if (pointlist.contains (point)) {return True ;} Else{/*point.status=point.statu_press;pointlist.add (point); */return false;}} public void Resetpointlist () {if (pointlist.size () >0) {-(int i = 0; i < pointlist.size (); I++) {point point=pointlis T.get (i);p oint.status=point.statu_normal;}} Pointlist.clear ();} public void Errorpoint () {to (point point:pointlist) {point.status=point.statu_error;}} /*** * Whether the checkpoint has intersection with nine Gongge points */private point checkPoint () {for (int i = 0; i < pointarray.length; i++) {for (int j = 0; J < pointarray[i].length; J + +) {point point=pointarray[i][j];if (isintersection (point, new Point (mcurrx,mcurry), mradior) {return point;}}} Return null;} /** * Initialize the pattern point */private void initpoint () {mscreenwidth=getwidth (); mscreenheight=getheight ();//cross screen if (mscreenwidth> Mscreenheight) {offsetx= (mscreenwidth-mscreenheight)/2;//square Screen lock mscreenwidth=mscreenheight;} Vertical screen else{offsety= (mscreenheight-mscreenwidth)/2;mscreenheight=mscreenwidth;} Mbitmapnormal=bitmapfactory.decoderesource (getresources (), normal); Mbitmappress=bitmapfactory.decoderesource ( Getresources (), press); mbitmaperror=bitmapfactory.decoderesource (getresources (), error); mbitmaplinepress= Bitmapfactory.decoderesource (getresources (), linepress); Mbitmaplineerror=bitmapfactory.decoderesource ( Getresources (), lineerror);p ointarray[0][0]=new Point (offsetx+mscreenwidth/4,offsety+mscreenwidth/4);p ointarray[ 0][1]=new Point (offsetx+mscreenwidth/2,offsety+mscreenwidth/4);p ointarray[0][2]=new Point (offsetx+ Mscreenwidth-mscreenwidth/4,offsety+mscreenwidth/4);p Ointarray[1][0]=new Point (offsetx+mscreenwidth/4,offsety+ Mscreenwidth/2);p ointarray[1][1]=new Point (offsetx+mscreenwidth/2,offsety+mscreenwidth/2);p ointarray[1][2]=new Point (offsetx+mscreenwidth-mscreenwidth/4,offsety+mscreenwidth/2);p ointarray[2][0]=new Point (offsetX+ Mscreenwidth/4,offsety+mscreenwidth-mscreenwidth/4);p Ointarray[2][1]=new Point (offsetx+mscreenwidth/2,offsety+Mscreenwidth-mscreenwidth/4);p Ointarray[2][2]=new Point (offsetx+mscreenwidth-mscreenwidth/4,offsety+ Mscreenwidth-mscreenwidth/4) mradior=mbitmapnormal.getwidth ()/2;int index=1;for (point[] point:pointArray) {for ( Point Mp:point) {mp.index=index;index++;}} isfirst=true;} /** * Draw the point collection onto the canvas */private void Pointtocanvas (canvas canvas) {for (int i = 0; i < pointarray.length; i++) {for (int j = 0; J < pointarray[i].length; J + +) {point mpoint=pointarray[i][j];if (mpoint.status==point.statu_normal) {canvas.drawbitmap (mBitmapNormal, mpoint.x-mradior, mpoint.y-mradior, mpaint);} else if (mpoint.status==point.statu_press) {canvas.drawbitmap (mbitmappress, mpoint.x-mradior, mPoint.y-mRadioR, mpaint);} else if (mpoint.status==point.statu_error) {canvas.drawbitmap (mbitmaperror, mpoint.x-mradior, mPoint.y-mRadioR, mpaint);}}} /*** * Get gesture Password * @return */private String getpassword () {//TODO auto-generated method stubstring mpassword= ""; for (int i = 0; I < pointlist.size (); I++) {point p=pointlist.get (i); MPASSWOrd+=string.valueof (p.index);/*for (int k = 0; k < pointarray.length; k++) {for (int j = 0; J < pointarray[k].length ; J + +) {point mp=pointarray[k][j];if (p==mp) {mpassword+=k+ "" +j;}}} */}return mpassword;} /** * Pattern Lock Point * @author Administrator * */public static class point{/** pattern lock three states: normal state */public static int statu_normal=0;/** pattern Three states of the lock: three states of the */public static int statu_press=1;/** pattern Lock: Error State */public The x.y point coordinates of the static int statu_error=2;/** pattern */public float x;public float y;public int index,status;public point () {}public point (float x,float y) {this.x=x;this.y=y;}} /** * Calculates the distance between two points * @param a * @param b * @return */public static double getdistance (point a,point b) {return math.sqrt (a.x- B.x) * (a.x-b.x) + (a.y-b.y) * (a.y-b.y));} /** * Determine if there is a intersection * @param a * @param b * @param r * @return */public static Boolean isintersection (point a,point b,float r) {r Eturn getdistance (a, B) <r;} public interface onlockpatternlistener{void onfail (); void Onsucceed (String password);} Private Onlockpatternlistener Listener;publIC void Setlistener (onlockpatternlistener listener) {this.listener = listener;}} </pre>Above is the custom control, the main usage: layout introduced view,activity or fragment to the control set listener callback function Judgment.<p><p></p></p><p><p>The main methods to use are as Follows:</p></p><p><p><br></p></p><pre name="code" class="java"><pre name="code" class="java">Handler Handler = new Handler ();p ublic void Updatelockpatern () {handler.postdelayed (new Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubif (!mlockpatern.isontouch) {mlockpatern.resetpointlist (); Mlockpatern.postinvalidate ();}}}, 1000);}</pre></pre><br><pre name="code" class="java"><pre name="code" class="java">@Overridepublic void Onfail () {//TODO auto-generated method stubsuper.onfail () mlocktoast.settext ("gesture Password connection at least 5 points");} @Overridepublic void Onsucceed (String password) {//TODO auto-generated method Stubsuper.onsucceed (password); BaseFragmentActivity.mLockPatern.getLock (). equals (PASSWORD)) { Intent intent=new Intent (getactivity (), apiclass.mlocklogin); StartActivity (intent); Getactivity (). Finish ();} else { mlocktoast.settext ("password is wrong, please redraw"); Mlockpatern.errorpoint (); Mlockpatern.postinvalidate (); Updatelockpatern ();}}</pre></pre><br>The project requires a resource file:<p><p></p></p><p><p><span style="color:#ff0000">nor.png, Press.png,error.png,linepress.png,lineerror.png</span></p></p><p><p>When the app is connected, consider the gesture password: A. Start the app, if you have a gesture password you need to enter a gesture password</p></p><p><p>B. Creating a gesture password</p></p><p><p>C. Modifying gesture passwords</p></p><p><p>D.onresume Life cycle monitor screen switch interval to determine the popup gesture password Interface.</p></p><p><p>Personally feel that the development with Baseactivity provides registerreceiver,lockpaternactivity extends fragmentactivity nested four fragmnent, According to intent incoming parameter selection fragment, I wrote the demo but no gesture encryption, I do not upload.</p></p><p><p>Android gesture Password</p></p></span>

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.