Android 화면 잠 금 원본 상세 설명 구현
1.비밀 번 호 를 설정 하지 않 았 을 때 시스템 설정 에 들 어 가 는 효과 도 는 다음 과 같 습 니 다.
2:비밀번호 설정 미리보기:
3:암호 복호화 효과 그림
4:구 궁 격 복호화 시 효과 도
다음은 간단하게 소스 코드 를 보 겠 습 니 다.여기 서 말씀 드 리 겠 습 니 다.이 작은 DEMO 도 임시로 배 웠 습 니 다.잘 모 르 는 부분 이 있 으 면 친구 에 게 직접 비판 하고 지적 하 세 요.잘못 이 있 으 면 반드시 고 칠 것 입 니 다.호 호 는 코드 를 보 겠 습 니 다.
주 제어 클래스:
package com.xiaoma.policymanager.demo;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
/**
* @Title: PolicySetupActivity.java
* @Package com.xiaoma.policymanager.demo
* @Description:
* @author MZH
*/
public class PolicySetupActivity extends Activity {
private static final int REQ_ACTIVATE_DEVICE_ADMIN = 10;
private static final String SCREEN_ID_KEY = "LAYOUT_ID";
/** SP */
private static final String APP_PREF = "APP_PREF";
/** ID */
private static final int UNKNOWN_SCREEN_ID = -1;
/** */
private Spinner mPasswordQualityInputField;
private EditText mPasswordLengthInputField;
private EditText mPasswordMinUppercaseInputField;
/**
*/
private Policy mPolicy;
/** ID*/
private int mCurrentScreenId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPolicy = new Policy(this);
}
@Override
protected void onResume() {
super.onResume();
/** SP */
SharedPreferences prefs = getSharedPreferences(APP_PREF, MODE_PRIVATE);
final int savedScreenId = prefs.getInt(SCREEN_ID_KEY, UNKNOWN_SCREEN_ID);
/** ID , */
if (savedScreenId == UNKNOWN_SCREEN_ID || !mPolicy.isAdminActive()) {
setScreenContent(R.layout.activity_policy_setup);
/** */
} else {
setScreenContent(savedScreenId);
}
}
/**
* , , ,
* .
* @param screenId
*/ private void setScreenContent(final int screenId) {
/** ID, SP */
mCurrentScreenId = screenId;
setContentView(mCurrentScreenId);
getSharedPreferences(APP_PREF, MODE_PRIVATE).edit().putInt(
SCREEN_ID_KEY, mCurrentScreenId).commit();
switch (mCurrentScreenId) {
case R.layout.activity_policy_setup:
initPolicySetupScreen();
initNavigation();
break;
case R.layout.activity_view_policy:
initViewPolicyScreen();
initNavigation();
break;
}
}
/**
* SP
*/
@Override
protected void onPause() {
super.onPause();
if (mCurrentScreenId == R.layout.activity_policy_setup) writePolicy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_ACTIVATE_DEVICE_ADMIN && resultCode == RESULT_OK) {
// User just activated the application as a device administrator.
setScreenContent(mCurrentScreenId);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
/**
* , ,
*/
@Override
public void onBackPressed() {
if (mCurrentScreenId == R.layout.activity_view_policy) {
setScreenContent(R.layout.activity_policy_setup);
return;
}
super.onBackPressed();
}
/**
*
*/
private void initPolicySetupScreen() {
mPasswordQualityInputField = (Spinner) findViewById(R.id.policy_password_quality);
mPasswordLengthInputField = (EditText) findViewById(R.id.policy_password_length);
mPasswordMinUppercaseInputField = (EditText) findViewById(R.id.policy_password_uppercase);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.password_types, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mPasswordQualityInputField.setAdapter(adapter);
mPasswordQualityInputField.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
LinearLayout passwordMinUppercaseView =
(LinearLayout) findViewById(R.id.password_uppercase_view);
// The minimum number of upper case field is only applicable for password
// qualities: alpha, alphanumeric, or complex.
if (pos > 2)
passwordMinUppercaseView.setVisibility(View.VISIBLE);
else
passwordMinUppercaseView.setVisibility(View.GONE);
}
public void onNothingSelected(AdapterView<?> parent) {}
});
/** */
mPolicy.readFromLocal();
mPasswordQualityInputField.setSelection(mPolicy.getPasswordQuality());
if (mPolicy.getPasswordLength() > 0) {
mPasswordLengthInputField.setText(String.valueOf(mPolicy.getPasswordLength()));
} else {
mPasswordLengthInputField.setText("");
}
if (mPolicy.getPasswordMinUpperCase() > 0) {
mPasswordMinUppercaseInputField.setText(
String.valueOf(mPolicy.getPasswordMinUpperCase()));
} else {
mPasswordMinUppercaseInputField.setText("");
}
}
/**
*
*/
private void initViewPolicyScreen() {
TextView passwordQualityView = (TextView) findViewById(R.id.policy_password_quality);
TextView passwordLengthView = (TextView) findViewById(R.id.policy_password_length);
// Read previously saved policy and populate on the UI.
mPolicy.readFromLocal();
int passwordQualitySelection = mPolicy.getPasswordQuality();
passwordQualityView.setText(
getResources().getStringArray(R.array.password_types)[passwordQualitySelection]);
passwordLengthView.setText(String.valueOf(mPolicy.getPasswordLength()));
if (passwordQualitySelection > 2) {
LinearLayout passwordMinUppercaseView =
(LinearLayout) findViewById(R.id.password_uppercase_view);
passwordMinUppercaseView.setVisibility(View.VISIBLE);
((TextView) findViewById(R.id.policy_password_uppercase)).setText(
String.valueOf(mPolicy.getPasswordMinUpperCase()));
}
}
/**
*
*/
private void initNavigation() {
if (!mPolic
y.isAdminActive()) {
// Activates device administrator.
setupNavigation(R.string.setup_message_activate,
R.string.setup_action_activate,
mActivateButtonListener);
} else if (mCurrentScreenId == R.layout.activity_policy_setup) {
setupNavigation(R.string.setup_message_set_policy,
R.string.setup_action_set_policy,
new View.OnClickListener() {
public void onClick(View view) {
writePolicy();
mPolicy.configurePolicy();
setScreenContent(R.layout.activity_view_policy);
}
});
}
else if (!mPolicy.isActivePasswordSufficient()) {
// Launches password set-up screen in Settings.
setupNavigation(R.string.setup_message_enforce_policy,
R.string.setup_action_enforce_policy,
mEnforcePolicyListener);
} else {
// Grants access to secure content.
setupNavigation(R.string.setup_message_go_secured,
R.string.setup_action_go_secured,
new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(view.getContext(), SecureActivity.class));
}
});
}
}
/**
* , .
*/
private View.OnClickListener mActivateButtonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// First, persist the policy. Then, launch intent to trigger the system screen
// requesting user to confirm the activation of the device administrator.
writePolicy();
Intent activateDeviceAdminIntent =
new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
activateDeviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
mPolicy.getPolicyAdmin());
// It is good practice to include the optional explanation text to explain to
// user why the application is requesting to be a device administrator.
The system
// will display this message on the activation screen.
activateDeviceAdminIntent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
getResources()
.getString(R.string.device_admin_activation_message));
startActivityForResult(activateDeviceAdminIntent, REQ_ACTIVATE_DEVICE_ADMIN);
}
};
/**
* , .
*/
private View.OnClickListener mEnforcePolicyListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
writePolicy();
// The device administration API does not "fix" the password if it is
// determined that the current password does not conform to what is requested
// by the policy. The caller is responsible for triggering the password set up
// screen via the below intent.
Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD);
startActivity(intent);
}
};
/**
*
* @param messageResId
* @param buttonTextResId
* @param listener
*/
private void setupNavigation(int messageResId, int buttonTextResId,
View.OnClickListener listener) {
TextView setupMessage = (TextView) findViewById(R.id.setup_message);
setupMessage.setText(messageResId);
Button actionBtn = (Button) findViewById(R.id.setup_action_btn);
actionBtn.setText(buttonTextResId);
actionBtn.setOnClickListener(listener);
}
// , SP .
private void writePolicy() {
int passwordQuality = (int) mPasswordQualityInputField.getSelectedItemId();
int passwordLength = 0;
try {
passwordLength = Integer.valueOf(mPasswordLengthInputField.getText().toString());
} catch (NumberFormatException nfe) {} // Defaults to 0.
int passwordMinUppercase = 0;
try {
passwordMinUppercase =
Integer.valueOf(mPasswordMinUppercaseInputField.getText().toString());
} catch (NumberFormatException nfe) {} // Defaults to 0.
mPolicy.saveToLocal(passwordQuality, passwordLength, passwordMinUppercase);
}
}
작업 클래스 설정:
package com.xiaoma.policymanager.demo;
import android.app.Activity;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
/**
*
@Title: Policy.java
* @Package com.xiaoma.policymanager.demo
* @Description:
* @author MZH */ public class Policy {
public static final int REQUEST_ADD_DEVICE_ADMIN = 1;
/** SP */
private static final String APP_PREF = "APP_PREF";
/** SP Key*/
private static final String KEY_PASSWORD_LENGTH = "PW_LENGTH";
private static final String KEY_PASSWORD_QUALITY = "PW_QUALITY";
private static final String KEY_PASSWORD_MIN_UPPERCASE = "PW_MIN_UPPERCASE";
/**
* , string.xml arrays.xml
*/ final static int[] PASSWORD_QUALITY_VALUES = new int[] {
DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED,
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING,
DevicePolicyManager.PASSWORD_QUALITY_NUMERIC,
DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC,
DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC,
DevicePolicyManager.PASSWORD_QUALITY_COMPLEX };
private int mPasswordQuality;
private int mPasswordLength;
private int mPasswordMinUpperCase;
private Context mContext;
private DevicePolicyManager mDPM;
private ComponentName mPolicyAdmin;
/**
* , new , DevicePolicyManager
*
@param context
*/
public Policy(Context context) {
mContext = context;
mPasswordQuality = -1;
mPasswordLength = 0;
mPasswordMinUpperCase = 0;
mDPM = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
mPolicyAdmin = new ComponentName(context, PolicyAdmin.class);
}
/**
*
*/
public void saveToLocal(int passwordQuality, int passwordLength, int passwordMinUppercase) {
SharedPreferences.Editor editor =
mContext.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE).edit();
if (mPasswordQuality != passwordQuality) {
editor.putInt(KEY_PASSWORD_QUALITY, passwordQuality);
mPasswordQuality = passwordQuality; }
if (mPasswordLength != passwordLength) {
editor.putInt(KEY_PASSWORD_LENGTH, passwordLength);
mPasswordLength = passwordLength;
}
if (mPasswordMinUpperCase != passwordMinUppercase) {
editor.putInt(KEY_PASSWORD_MIN_UPPERCASE, passwordMinUppercase);
mPasswordMinUpperCase = passwordMinUppercase;
} editor.commit();
}
/**
* SP
*/
public void readFromLocal() {
SharedPreferences prefs = mContext.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE);
mPasswordQuality = prefs.getInt(KEY_PASSWORD_QUALITY, -1);
mPasswordLength = prefs.getInt(KEY_PASSWORD_LENGTH, -1);
mPasswordMinUpperCase = prefs.getInt(KEY_PASSWORD_MIN_UPPERCASE, -1);
}
/**
* .
*
* @return
*/
public int getPasswordQuality() { return mPasswordQuality; }
/**
* .
*
* @return
*/
public int getPasswordLength() { return mPasswordLength; }
/**
* .
*
* @return
*/
public int getPasswordMinUpperCase() { return mPasswordMinUpperCase; }
/**
* ComponentName .
*
* @return
*/
public ComponentName getPolicyAdmin() { return mPolicyAdmin; }
/**
* .
*
* @return
*/
public boolean isAdminActive() {
return mDPM.isAdminActive(mPolicyAdmin);
}
public boolean isActivePasswordSufficient() {
return mDPM.isActivePasswordSufficient();
}
/**
*
* @return
*/
public boolean isDeviceSecured() {
return isAdminActive() && isActiveP
asswordSufficient(); }
/**
* mDPM .
*/
public void configurePolicy() {
mDPM.setPasswordQuality(mPolicyAdmin, PASSWORD_QUALITY_VALUES[mPasswordQuality]);
mDPM.setPasswordMinimumLength(mPolicyAdmin, mPasswordLength);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mDPM.setPasswordMinimumUpperCase(mPolicyAdmin, mPasswordMinUpperCase);
}
}
/**
* , :
*/
public static class PolicyAdmin extends DeviceAdminReceiver {
@Override
public void onDisabled(Context context, Intent intent) {
// Called when the app is about to be deactivated as a device administrator.
super.onDisabled(context, intent);
SharedPreferences prefs = context.getSharedPreferences(APP_PREF, Activity.MODE_PRIVATE);
/** SP */
prefs.edit().clear().commit();
}
}
}
권한 검증 클래스:
package com.xiaoma.policymanager.demo;
import android.app.Activity;
import android.content.Intent;
/**
* @Title: SecureActivity.java
* @Package com.xiaoma.policymanager.demo
* @Description:
* @author MZH
*/
public class SecureActivity extends Activity {
@Override
protected void onResume() {
super.onResume();
// Check to see if the device is properly secured as per the policy. Send user
// back to policy set up screen if necessary.
Policy policy = new Policy(this);
policy.readFromLocal();
if (!policy.isDeviceSecured()) {
Intent intent = new Intent();
intent.setClass(this, PolicySetupActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
setContentView(R.layout.activity_secure);
}
}
본 고 에서 말 한 것 이 당신 에 게 도움 이 되 기 를 바 랍 니 다.안 드 로 이 드 는 화면 잠 금 소스 코드 를 실현 하 는 상세 한 내용 을 소개 합 니 다.저희 사 이 트 를 계속 지 켜 봐 주시 기 바 랍 니 다!안 드 로 이 드 를 배우 고 싶 으 면 본 사이트 에 계속 관심 을 가 져 도 됩 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.