Android实现屏幕锁定源码详解
程序员文章站
2024-03-04 21:23:18
最近有朋友问屏幕锁定的问题,自己也在学习,网上找了下也没太详细的例子,看的资料书上也没有有关屏幕锁定程序的介绍,下个小决心,自己照着官方文档学习下,现在做好了,废话不多说,...
最近有朋友问屏幕锁定的问题,自己也在学习,网上找了下也没太详细的例子,看的资料书上也没有有关屏幕锁定程序的介绍,下个小决心,自己照着官方文档学习下,现在做好了,废话不多说,先发下截图,看下效果,需要注意的地方会加注释,有问题的朋友可以直接留言,我们共同学习交流,共同提高进步!直接看效果图:
一:未设置密码时进入系统设置的效果图如下:
二:设置密码方式预览:
三:密码解密效果图
四:九宫格解密时的效果图
下面来简单的看下源码吧,此处讲下,这个小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可以继续关注本站。