Android仿手機(jī)QQ圖案解鎖功能
本文實(shí)例為大家分享了Android仿手機(jī)QQ圖案解鎖的具體代碼,供大家參考,具體內(nèi)容如下
ps:請不要再問我,為什么導(dǎo)入之后會亂碼了。
其實(shí),代碼基本上都是從原生系統(tǒng)中提取的:LockPatternView、加密工具類,以及解鎖邏輯等,我只是稍作修改,大家都知道,原生系統(tǒng)界面比較丑陋,因此,我特意把QQ的apk解壓了,從中拿了幾張圖案解鎖的圖片,一個(gè)簡單的例子就這樣誕生了。
好了,廢話不多說,我們來看看效果(最后兩張是最新4.4系統(tǒng),炫一下,呵呵):




1.最關(guān)健的就是那個(gè)自定義九宮格View,代碼來自framework下:LockPatternView,原生系統(tǒng)用的圖片資源比較多,好像有7、8張吧,而且繪制的比較復(fù)雜,我找尋半天,眼睛都找瞎了,發(fā)現(xiàn)解壓的QQ里面就3張圖片,一個(gè)圈圈,兩個(gè)點(diǎn),沒辦法,只能修改代碼了,在修改的過程中,才發(fā)現(xiàn),其實(shí)可以把原生的LockPatternView給簡化,繪制更少的圖片,達(dá)到更好的效果??偣矁?yōu)化有:①去掉了連線的箭頭,②原生的連線只有白色一種,改成根據(jù)不同狀態(tài)顯示黃色和紅色兩張色,③.原生view是先畫點(diǎn)再畫線,使得線覆蓋在點(diǎn)的上面,影響美觀,改成先畫連線再畫點(diǎn)。
關(guān)健部分代碼onDraw函數(shù):
@Override
protected void onDraw(Canvas canvas) {
final ArrayList<Cell> pattern = mPattern;
final int count = pattern.size();
final boolean[][] drawLookup = mPatternDrawLookup;
if (mPatternDisplayMode == DisplayMode.Animate) {
// figure out which circles to draw
// + 1 so we pause on complete pattern
final int oneCycle = (count + 1) * MILLIS_PER_CIRCLE_ANIMATING;
final int spotInCycle = (int) (SystemClock.elapsedRealtime() - mAnimatingPeriodStart)
% oneCycle;
final int numCircles = spotInCycle / MILLIS_PER_CIRCLE_ANIMATING;
clearPatternDrawLookup();
for (int i = 0; i < numCircles; i++) {
final Cell cell = pattern.get(i);
drawLookup[cell.getRow()][cell.getColumn()] = true;
}
// figure out in progress portion of ghosting line
final boolean needToUpdateInProgressPoint = numCircles > 0
&& numCircles < count;
if (needToUpdateInProgressPoint) {
final float percentageOfNextCircle = ((float) (spotInCycle % MILLIS_PER_CIRCLE_ANIMATING))
/ MILLIS_PER_CIRCLE_ANIMATING;
final Cell currentCell = pattern.get(numCircles - 1);
final float centerX = getCenterXForColumn(currentCell.column);
final float centerY = getCenterYForRow(currentCell.row);
final Cell nextCell = pattern.get(numCircles);
final float dx = percentageOfNextCircle
* (getCenterXForColumn(nextCell.column) - centerX);
final float dy = percentageOfNextCircle
* (getCenterYForRow(nextCell.row) - centerY);
mInProgressX = centerX + dx;
mInProgressY = centerY + dy;
}
// TODO: Infinite loop here...
invalidate();
}
final float squareWidth = mSquareWidth;
final float squareHeight = mSquareHeight;
float radius = (squareWidth * mDiameterFactor * 0.5f);
mPathPaint.setStrokeWidth(radius);
final Path currentPath = mCurrentPath;
currentPath.rewind();
// TODO: the path should be created and cached every time we hit-detect
// a cell
// only the last segment of the path should be computed here
// draw the path of the pattern (unless the user is in progress, and
// we are in stealth mode)
final boolean drawPath = (!mInStealthMode || mPatternDisplayMode == DisplayMode.Wrong);
// draw the arrows associated with the path (unless the user is in
// progress, and
// we are in stealth mode)
boolean oldFlag = (mPaint.getFlags() & Paint.FILTER_BITMAP_FLAG) != 0;
mPaint.setFilterBitmap(true); // draw with higher quality since we
// render with transforms
// draw the lines
if (drawPath) {
boolean anyCircles = false;
for (int i = 0; i < count; i++) {
Cell cell = pattern.get(i);
// only draw the part of the pattern stored in
// the lookup table (this is only different in the case
// of animation).
if (!drawLookup[cell.row][cell.column]) {
break;
}
anyCircles = true;
float centerX = getCenterXForColumn(cell.column);
float centerY = getCenterYForRow(cell.row);
if (i == 0) {
currentPath.moveTo(centerX, centerY);
} else {
currentPath.lineTo(centerX, centerY);
}
}
// add last in progress section
if ((mPatternInProgress || mPatternDisplayMode == DisplayMode.Animate)
&& anyCircles) {
currentPath.lineTo(mInProgressX, mInProgressY);
}
// chang the line color in different DisplayMode
if (mPatternDisplayMode == DisplayMode.Wrong)
mPathPaint.setColor(Color.RED);
else
mPathPaint.setColor(Color.YELLOW);
canvas.drawPath(currentPath, mPathPaint);
}
// draw the circles
final int paddingTop = getPaddingTop();
final int paddingLeft = getPaddingLeft();
for (int i = 0; i < 3; i++) {
float topY = paddingTop + i * squareHeight;
// float centerY = mPaddingTop + i * mSquareHeight + (mSquareHeight
// / 2);
for (int j = 0; j < 3; j++) {
float leftX = paddingLeft + j * squareWidth;
drawCircle(canvas, (int) leftX, (int) topY, drawLookup[i][j]);
}
}
mPaint.setFilterBitmap(oldFlag); // restore default flag
}
2.第二個(gè)值得學(xué)習(xí)的地方是(代碼來自設(shè)置應(yīng)用中):在創(chuàng)建解鎖圖案時(shí)的枚舉使用,原生代碼中使用了很多枚舉,將繪制圖案時(shí)的狀態(tài)、底部兩個(gè)按鈕狀態(tài)、頂部一個(gè)TextView顯示的提示文字都緊密的聯(lián)系起來。因此,只用監(jiān)聽LockPatternView動態(tài)變化,對應(yīng)改變底部Button和頂部TextView的狀態(tài)即可實(shí)現(xiàn)聯(lián)動,簡單的方法可以實(shí)現(xiàn)很多代碼才能實(shí)現(xiàn)的邏輯,個(gè)人很喜歡。
①全局的狀態(tài):
/**
* Keep track internally of where the user is in choosing a pattern.
*/
protected enum Stage {
// 初始狀態(tài)
Introduction(R.string.lockpattern_recording_intro_header,
LeftButtonMode.Cancel, RightButtonMode.ContinueDisabled,
ID_EMPTY_MESSAGE, true),
// 幫助狀態(tài)
HelpScreen(R.string.lockpattern_settings_help_how_to_record,
LeftButtonMode.Gone, RightButtonMode.Ok, ID_EMPTY_MESSAGE,
false),
// 繪制過短
ChoiceTooShort(R.string.lockpattern_recording_incorrect_too_short,
LeftButtonMode.Retry, RightButtonMode.ContinueDisabled,
ID_EMPTY_MESSAGE, true),
// 第一次繪制圖案
FirstChoiceValid(R.string.lockpattern_pattern_entered_header,
LeftButtonMode.Retry, RightButtonMode.Continue,
ID_EMPTY_MESSAGE, false),
// 需要再次繪制確認(rèn)
NeedToConfirm(R.string.lockpattern_need_to_confirm,
LeftButtonMode.Cancel, RightButtonMode.ConfirmDisabled,
ID_EMPTY_MESSAGE, true),
// 確認(rèn)出錯(cuò)
ConfirmWrong(R.string.lockpattern_need_to_unlock_wrong,
LeftButtonMode.Cancel, RightButtonMode.ConfirmDisabled,
ID_EMPTY_MESSAGE, true),
// 選擇確認(rèn)
ChoiceConfirmed(R.string.lockpattern_pattern_confirmed_header,
LeftButtonMode.Cancel, RightButtonMode.Confirm,
ID_EMPTY_MESSAGE, false);
/**
* @param headerMessage
* The message displayed at the top.
* @param leftMode
* The mode of the left button.
* @param rightMode
* The mode of the right button.
* @param footerMessage
* The footer message.
* @param patternEnabled
* Whether the pattern widget is enabled.
*/
Stage(int headerMessage, LeftButtonMode leftMode,
RightButtonMode rightMode, int footerMessage,
boolean patternEnabled) {
this.headerMessage = headerMessage;
this.leftMode = leftMode;
this.rightMode = rightMode;
this.footerMessage = footerMessage;
this.patternEnabled = patternEnabled;
}
final int headerMessage;
final LeftButtonMode leftMode;
final RightButtonMode rightMode;
final int footerMessage;
final boolean patternEnabled;
}
②.底部兩個(gè)按鈕的狀態(tài)枚舉:
/**
* The states of the left footer button.
*/
enum LeftButtonMode {
// 取消
Cancel(android.R.string.cancel, true),
// 取消時(shí)禁用
CancelDisabled(android.R.string.cancel, false),
// 重試
Retry(R.string.lockpattern_retry_button_text, true),
// 重試時(shí)禁用
RetryDisabled(R.string.lockpattern_retry_button_text, false),
// 消失
Gone(ID_EMPTY_MESSAGE, false);
/**
* @param text
* The displayed text for this mode.
* @param enabled
* Whether the button should be enabled.
*/
LeftButtonMode(int text, boolean enabled) {
this.text = text;
this.enabled = enabled;
}
final int text;
final boolean enabled;
}
/**
* The states of the right button.
*/
enum RightButtonMode {
// 繼續(xù)
Continue(R.string.lockpattern_continue_button_text, true),
//繼續(xù)時(shí)禁用
ContinueDisabled(R.string.lockpattern_continue_button_text, false),
//確認(rèn)
Confirm(R.string.lockpattern_confirm_button_text, true),
//確認(rèn)是禁用
ConfirmDisabled(R.string.lockpattern_confirm_button_text, false),
//OK
Ok(android.R.string.ok, true);
/**
* @param text
* The displayed text for this mode.
* @param enabled
* Whether the button should be enabled.
*/
RightButtonMode(int text, boolean enabled) {
this.text = text;
this.enabled = enabled;
}
final int text;
final boolean enabled;
}
就這樣,只要LockPatternView的狀態(tài)一發(fā)生改變,就會動態(tài)改變底部兩個(gè)Button的文字和狀態(tài)。很簡潔,邏輯性很強(qiáng)。
3.第三個(gè)個(gè)人覺得比較有用的就是加密這一塊了,為了以后方便使用,我把圖案加密和字符加密分成兩個(gè)工具類:LockPatternUtils和LockPasswordUtils兩個(gè)文件,本文使用到的是LockPatternUtils。其實(shí)所謂的圖案加密也是將其通過SHA-1加密轉(zhuǎn)化成二進(jìn)制數(shù)再保存到文件中(原生系統(tǒng)保存在/system/目錄下,我這里沒有權(quán)限,就保存到本應(yīng)用目錄下),解密時(shí),也是將獲取到用戶的輸入通過同樣的方法加密,再與保存到文件中的對比,相同則密碼正確,不同則密碼錯(cuò)誤。關(guān)健代碼就是以下4個(gè)函數(shù):
/**
* Serialize a pattern. 加密
*
* @param pattern
* The pattern.
* @return The pattern in string form.
*/
public static String patternToString(List<LockPatternView.Cell> pattern) {
if (pattern == null) {
return "";
}
final int patternSize = pattern.size();
byte[] res = new byte[patternSize];
for (int i = 0; i < patternSize; i++) {
LockPatternView.Cell cell = pattern.get(i);
res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
}
return new String(res);
}
/**
* Save a lock pattern.
*
* @param pattern
* The new pattern to save.
* @param isFallback
* Specifies if this is a fallback to biometric weak
*/
public void saveLockPattern(List<LockPatternView.Cell> pattern) {
// Compute the hash
final byte[] hash = LockPatternUtils.patternToHash(pattern);
try {
// Write the hash to file
RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename,
"rwd");
// Truncate the file if pattern is null, to clear the lock
if (pattern == null) {
raf.setLength(0);
} else {
raf.write(hash, 0, hash.length);
}
raf.close();
} catch (FileNotFoundException fnfe) {
// Cant do much, unless we want to fail over to using the settings
// provider
Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
} catch (IOException ioe) {
// Cant do much
Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename);
}
}
/*
* Generate an SHA-1 hash for the pattern. Not the most secure, but it is at
* least a second level of protection. First level is that the file is in a
* location only readable by the system process.
*
* @param pattern the gesture pattern.
*
* @return the hash of the pattern in a byte array.
*/
private static byte[] patternToHash(List<LockPatternView.Cell> pattern) {
if (pattern == null) {
return null;
}
final int patternSize = pattern.size();
byte[] res = new byte[patternSize];
for (int i = 0; i < patternSize; i++) {
LockPatternView.Cell cell = pattern.get(i);
res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
}
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hash = md.digest(res);
return hash;
} catch (NoSuchAlgorithmException nsa) {
return res;
}
}
/**
* Check to see if a pattern matches the saved pattern. If no pattern
* exists, always returns true.
*
* @param pattern
* The pattern to check.
* @return Whether the pattern matches the stored one.
*/
public boolean checkPattern(List<LockPatternView.Cell> pattern) {
try {
// Read all the bytes from the file
RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename,
"r");
final byte[] stored = new byte[(int) raf.length()];
int got = raf.read(stored, 0, stored.length);
raf.close();
if (got <= 0) {
return true;
}
// Compare the hash from the file with the entered pattern's hash
return Arrays.equals(stored,
LockPatternUtils.patternToHash(pattern));
} catch (FileNotFoundException fnfe) {
return true;
} catch (IOException ioe) {
return true;
}
}
好了,代碼就分析到這里,非常感謝你看到了文章末尾。
本文源碼(utf-8編碼):Android仿手機(jī)QQ圖案解鎖
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android如何實(shí)現(xiàn)社交應(yīng)用中的評論與回復(fù)功能詳解
目前,各種App的社區(qū)或者用戶曬照片、發(fā)說說的地方,都提供了評論功能,為了更好地學(xué)習(xí),自己把這個(gè)功能實(shí)現(xiàn)了一下,下面這篇文章主要給大家介紹了關(guān)于Android如何實(shí)現(xiàn)社交應(yīng)用中的評論與回復(fù)功能的相關(guān)資料,需要的朋友可以參考下2018-07-07
音量控制鍵控制的音頻流(setVolumeControlStream)描述
當(dāng)開發(fā)多媒體應(yīng)用或者游戲應(yīng)用的時(shí)候,需要使用音量控制鍵來設(shè)置程序的音量大小,在Android系統(tǒng)中有多種音頻流,感興趣的朋友可以了解下2013-01-01
Android開發(fā)歡迎頁點(diǎn)擊跳過倒計(jì)時(shí)進(jìn)入主頁
沒點(diǎn)擊跳過自然進(jìn)入主頁,點(diǎn)擊跳過之后立即進(jìn)入主頁,這個(gè)功能怎么實(shí)現(xiàn)呢,本文通過實(shí)例代碼給大家介紹Android開發(fā)歡迎頁點(diǎn)擊跳過倒計(jì)時(shí)進(jìn)入主頁,感興趣的朋友一起看看吧2023-12-12
Android粒子線條效果實(shí)現(xiàn)過程與代碼
這篇文章主要介紹了Android粒子線條效果的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02
Android UI設(shè)計(jì)系列之自定義DrawView組件實(shí)現(xiàn)數(shù)字簽名效果(5)
這篇文章主要介紹了Android UI設(shè)計(jì)系列之自定義DrawView組件實(shí)現(xiàn)數(shù)字簽名效果,具有一定的實(shí)用性和參考價(jià)值,感興趣的小伙伴們可以參考一下2016-06-06
Win8下Android SDK安裝與環(huán)境變量配置教程
這篇文章主要為大家詳細(xì)介紹了Win8下Android SDK安裝與環(huán)境變量配置教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07
Android getSystemService用法實(shí)例總結(jié)
這篇文章主要介紹了Android getSystemService用法,結(jié)合實(shí)例形式總結(jié)分析了getSystemService獲取系統(tǒng)Service的相關(guān)使用方法與注意事項(xiàng),需要的朋友可以參考下2016-01-01
Android使用CountDownTimer實(shí)現(xiàn)倒計(jì)時(shí)效果
這篇文章主要為大家詳細(xì)介紹了Android使用CountDownTimer實(shí)現(xiàn)倒計(jì)時(shí)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09

