Android实现屏幕锁定源码详解

最近有朋友问屏幕锁定的问题,自己也在学习,网上找了下也没太详细的例子,看的资料书上也没有有关屏幕锁定程序的介绍,下个小决心,自己照着官方文档学习下,现在做好了,废话不多说,先发下截图,看下效果,需要注意的地方会加注释,有问题的朋友可以直接留言,我们共同学习交流,共同提高进步!直接看效果图:

一:未设置密码时进入系统设置的效果图如下:

二:设置密码方式预览:

三:密码解密效果图

四:九宫格解密时的效果图

下面来简单的看下源码吧,此处讲下,这个小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);
}
}

希望本文所述对你有所帮助,Android实现屏幕锁定源码详解内容就给大家介绍到这里了。希望大家继续关注我们的网站!想要学习Android可以继续关注本站。

(0)

相关推荐

  • 轻松实现Android锁屏功能

    锁屏需要引入设备超级管理员.在文档Android开发文档的Administration中有详细的说明.Android设备管理系统功能和控制访问. 主要有一下几个步骤: 1  创建广播接收者,实现DeviceAdminReceiver package com.andy.lockscreen; import android.app.admin.DeviceAdminReceiver; /** * @author Zhang,Tianyou * @version 2014年11月20日 下午9:51:

  • Android系统永不锁屏永不休眠的方法

    开发Android程序时,有时候在程序运行的时候,不能让系统休眠,否则有一些运行会停止,因此我们需要设置禁止休眠,有两种方式:        一种是添加权限,              一种是代码中设置, 建议使用第一种方式,这样,在安装程序的时候会进行提醒: 第一种方式: 在Manifest.xml文件里面用user-permission声明 名称为:android.permission.WAKE_LOCK 第二种方式: getWindow().setFlags(WindowManager.L

  • Android编程之自定义锁屏实例分析

    本文实例讲述了Android编程之自定义锁屏.分享给大家供大家参考,具体如下: 花了半天时间研究下了自定义锁屏,发现其实实现并不是很神秘.不过有些地方还是值得注意. 首先说流程,锁屏界面一般是在关闭屏幕时启用,打开屏幕时展现在我们面前,所以我们知道了锁屏的时机,恰好屏幕开关会发出相应的广播,所以我们也可以像系统一样捕获到屏幕开关的事件. 广播对应的两个action 引用 android.intent.action.SCREEN_ON android.intent.action.SCREEN_OF

  • Android编程实现一键锁屏的方法

    本文实例讲述了Android编程实现一键锁屏的方法.分享给大家供大家参考,具体如下: 这里要用到下面两个类: DeviceAdminReceiver 设备管理组件.这个类提供了一个方便解释由系统发出的意图的动作.你的设备管理应用程序必须包含一个DeviceAdminReceiver的子类.本程序中,就代表一个手机上的设备管理器. DevicePolicyManager 一个管理设备上规范的类. 大多数客户端必须声明一个用户当前已经启用的DeviceAdminReceiver. 这个DeviceP

  • Android开发实现消除屏幕锁的方法

    本文实例讲述了Android开发实现消除屏幕锁的方法.分享给大家供大家参考,具体如下: 实现屏幕无锁--->当我们开机或者超过锁屏幕时间或按电源键之后屏幕没有锁的一种状态. 经过查询许多资料以及分析代码,我们可以发现最主要的屏幕功能还是在framework/base/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java中. 里面有一个handleshow方法: 真正的去锁屏实现有一个 handlehide方法,

  • Android如何实现锁屏状态下弹窗

    前言 想在锁屏上面实现弹窗,第一个想法就是利用 WindowManager 设置 Window 的 Flag,通过设置 Flag 的显示优先级来让窗口显示在锁屏的上面. 接下来就是试验可能相关的 Window Type 属性,验证该方案是否可行. 在尝试各个 Window Type 属性之前需要明确各个 Type 所需要的权限,下面是 com.android.internal.policy.impl.PhoneWindowManager.checkAddPermission 的源码: publi

  • Android唤醒、解锁屏幕代码实例

    解锁.唤醒屏幕用到KeyguardManager,KeyguardLock,PowerManager,PowerManager.WakeLock   所需权限: 复制代码 代码如下: <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /&

  • Android屏幕锁屏弹窗的正确姿势DEMO详解

    在上篇文章给大家介绍了Android程序开发仿新版QQ锁屏下弹窗功能.今天通过本文给大家分享android锁屏弹窗的正确姿势. 最近在做一个关于屏幕锁屏悬浮窗的功能,于是在网上搜索了很多安卓屏幕锁屏的相关资料,鉴于网上的资料比较零碎,所以我在这里进行整理总结.本文将从以下两点对屏幕锁屏进行解析: 1. 如何监听系统屏幕锁屏 2. 如何在锁屏界面弹出悬浮窗 如何监听系统屏幕锁屏 经过总结,监听系统的锁屏可以通过以下两种方式: 1) 代码直接判定 2) 接收广播 1) 代码直接判定 代码判断方式,也

  • Android编程实现的一键锁屏程序详解

    本文实例讲述了Android编程实现的一键锁屏程序.分享给大家供大家参考,具体如下: 据笔者了解,所有的Android手机都用电源键来手动锁屏.笔者使用手机时,一天之内手动锁屏的次数绝对不少于30次.如果都用电源键来进行的话,那么电源键的使用寿命一定不会长久. 虽然现在有很多的桌面软件都集成了一键锁屏,但是要安装这些软件就必须安装它们的其他组件,这点让人很不爽,因为他们会定期自动更新,或者在后台运行一些我不想要的东西.所以我决定自己写一个锁屏程序. 经过在android开发文档里面的查找,我发现

  • android禁止锁屏保持常亮(示例代码)

    在播放video的时候在mediaplayer mMediaPlayer.setScreenOnWhilePlaying(true); 已经设置了,在原生的android没有问题和在defy上也没有问题,一到三星的galaxy上就有问题,不知道三星他们改了哪些地方.一般的话设置了播放视频屏幕没有自动.但是在三星上就出了问题. 只好再找找.一般的话设置有两种方法. 如下: 复制代码 代码如下: 1. getWindow().addFlags(WindowManager.LayoutParams.F

随机推荐