文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android实现屏幕锁定源码详解

2022-06-06 07:09

关注

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

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

 

二:设置密码方式预览:

三:密码解密效果图

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

下面来简单的看下源码吧,此处讲下,这个小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;
  
  public class PolicySetupActivity extends Activity {
  private static final int REQ_ACTIVATE_DEVICE_ADMIN = 10;
  private static final String SCREEN_ID_KEY = "LAYOUT_ID";
  
  private static final String APP_PREF = "APP_PREF";
  
  private static final int UNKNOWN_SCREEN_ID = -1;
  
  private Spinner mPasswordQualityInputField;
  private EditText mPasswordLengthInputField;
  private EditText mPasswordMinUppercaseInputField;
  
  private Policy mPolicy;
  
  private int mCurrentScreenId;
  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  mPolicy = new Policy(this);
  }
  @Override
  protected void onResume() {
  super.onResume();
  
  SharedPreferences prefs = getSharedPreferences(APP_PREF, MODE_PRIVATE);
  final int savedScreenId = prefs.getInt(SCREEN_ID_KEY, UNKNOWN_SCREEN_ID);
  
  if (savedScreenId == UNKNOWN_SCREEN_ID || !mPolicy.isAdminActive()) {
  setScreenContent(R.layout.activity_policy_setup);
  
  } else {
  setScreenContent(savedScreenId);
  }
  }
     private void setScreenContent(final int screenId) {
  
  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;
  }
  }
  
  @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);
  }
  };
  
  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;
   public class Policy {
  public static final int REQUEST_ADD_DEVICE_ADMIN = 1;
  
  private static final String APP_PREF = "APP_PREF";
  
  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";
     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;
  
  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();
  }
  
  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);
  }
  
  public int getPasswordQuality() { return mPasswordQuality; }
  
  public int getPasswordLength() { return mPasswordLength; }
  
  public int getPasswordMinUpperCase() { return mPasswordMinUpperCase; }
  
  public ComponentName getPolicyAdmin() { return mPolicyAdmin; }
  
  public boolean isAdminActive() {
  return mDPM.isAdminActive(mPolicyAdmin);
  }
  public boolean isActivePasswordSufficient() {
  return mDPM.isActivePasswordSufficient();
  }
  
  public boolean isDeviceSecured() {
  return isAdminActive() && isActiveP
  asswordSufficient();   }
  
  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);
  
  prefs.edit().clear().commit();
  }
  }
  }

权限验证类:


package com.xiaoma.policymanager.demo;
import android.app.Activity;
import android.content.Intent;

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可以继续关注本站。

您可能感兴趣的文章:Android屏幕锁屏弹窗的正确姿势DEMO详解Android唤醒、解锁屏幕代码实例Android编程实现一键锁屏的方法android禁止锁屏保持常亮(示例代码)Android如何实现锁屏状态下弹窗Android系统永不锁屏永不休眠的方法Android编程实现的一键锁屏程序详解Android编程之自定义锁屏实例分析轻松实现Android锁屏功能Android开发实现消除屏幕锁的方法


阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯