Android to achieve screen lock source detailed _android

Source: Internet
Author: User
Tags gettext static class

Recently, a friend asked the problem of the screen lock, they are also learning, online look for the next not too detailed examples, look at the information book on the screen locking procedures, the next small determination to follow the official document study, now done, nonsense not to say, first send a screenshot, look at the effect, need to pay attention to the place will be added notes, Friends with problems can be directly message, we learn to communicate together, improve progress together! See the effect chart directly:

One: The effect of entering system settings without setting a password is as follows:

Two: Set the password way to preview:

Three: Password decryption effect chart

4:9 Sudoku Decryption Effect diagram

The following is a simple look at the source code, here, this small demo is also a temporary learning, there is no understanding of the place to ask a friend direct criticism pointed out that the mistake must be changed, Roar look code:

Main control class:

 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.vi ew. 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.Te
  Xtview/** * @Title: Policysetupactivity.java * @Package Com.xiaoma.policymanager.demo * @Description: Screen lock implementation test * @author Mzh */public class Policysetupactivity extends activity {private static final int Req_activate_device_ad MIN = Ten private static final string Screen_id_key = "layout_id";/** SP file name for storage configuration information */private static final string APP _pref = "App_pref"; returns this identity when/** has an unknown screen ID * * private static final int unknown_screen_id =-1;/** declaration component/Private Spinner MpasswordqualityinputField; private edittext Mpasswordlengthinputfield; private edittext Mpasswordminuppercaseinputfield/** get Configuration Action Class object * Private Policy mpolicy/** current screen id*/private int mcurrentscreenid; @Override public void onCreate (Bundle saved Instancestate) {super.oncreate (savedinstancestate); mpolicy = new Policy (this);} @Override protected void onre Sume () {super.onresume ();/** Gets the configuration information for the screen lock in the local SP file/sharedpreferences prefs = getsharedpreferences (App_pref, Mode_priv ATE); final int savedscreenid = Prefs.getint (Screen_id_key, unknown_screen_id);/** If the ID obtained is empty, jumps to the Settings page/if (SAVEDSCR Eenid = = UNKNOWN_SCREEN_ID | | ! Mpolicy.isadminactive ()) {setscreencontent (r.layout.activity_policy_setup);/** jumps to the configuration details page * *} else {Setscreenconte NT (Savedscreenid);}/** * Set the screen method implementation, detailed you can see for yourself, I am also in the reference to official documents, while learning the * have good ideas have problems friends can leave a message. We study together * @param Screenid * /private void Setscreencontent (final int screenid) {/** record the current screen ID and deposit it in advance in the local SP profile * * Mcurrentscreenid = ScreeniD; Setcontentview (Mcurrentscreenid); Getsharedpreferences (App_pref, Mode_private). Edit (). Putint (SCREEN_ID_KEY, MCu
  Rrentscreenid). commit (); switch (Mcurrentscreenid) {case R.layout.activity_policy_setup:initpolicysetupscreen ();
  Initnavigation (), break, Case R.layout.activity_view_policy:initviewpolicyscreen (), initnavigation (); }/** * Writes the current configuration to the local SP file when closing the page */@Override protected void OnPause () {super.onpause (); if (Mcurrentscreen Id = = R.layout.activity_policy_setup) writepolicy ();} @Override protected void Onactivityresult (int requestcode, in T ResultCode, Intent data) {if (Requestcode = = Req_activate_device_admin && ResultCode = = RESULT_OK) {//Use
  R just activated the application as a device administrator. Setscreencontent (Mcurrentscreenid);} else {Super.onactivityresult (Requestcode, ResultCode, data);}/** * Overload return key method, if the current screen is already set the Password page, the display details * * @Override public void onbackpressed () {if (m)Currentscreenid = = R.layout.activity_view_policy) {setscreencontent (r.layout.activity_policy_setup); Super.onbackpressed ();}/** * Initialization Settings page * * private void Initpolicysetupscreen () {Mpasswordqualityinputfield = (Spinner) Findviewbyid (r.id.policy_password_quality); Mpasswordlengthinputfield = (EditText) Findviewbyid (R.id.pol Icy_password_length); Mpasswordminuppercaseinputfield = (EditText) Findviewbyid (r.id.policy_password_uppercase); rrayadapter<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&LT;?
> Parent, view view, int pos, long id {linearlayout Passwordminuppercaseview =  (linearlayout) Findviewbyid (R.id.password_uppercase_view);//The minimum number of upper case field are only applicabl
  E for password//Qualities:alpha, alphanumeric, or complex. if (pos > 2) passwordminuppercaseview.setvisibility (view.visible); else Passwordminuppercaseview.setvisibility (Vi ew. GONE);} public void onnothingselected (ADAPTERVIEW&LT;? > Parent) {}}/** read previously configured information/mpolicy.readfromlocal (); Mpasswordqualityinputfield.setselection (MPOLICY.GETP
  Asswordquality ()); if (Mpolicy.getpasswordlength () > 0) {
  Mpasswordlengthinputfield.settext (String.valueof (Mpolicy.getpasswordlength ()));} else { Mpasswordlengthinputfield.settext ("");} if (Mpolicy.getpasswordminuppercase () > 0) {mpasswordminuppercaseinputf Ield.settext (String.valueof (Mpolicy.getpasswordminuppercase ()));} else {Mpasswordminuppercaseinputfield.settext ( "");}/** * Initialize view details page/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 (g Etresources (). Getstringarray (R.array.password_types) [passwordqualityselection]); passwordlengthview.settext (String.valueof (Mpolicy.getpasswordlength ())); if (Passwordqualityselection > 2) {linearlayout PasswordMinUpperca
  Seview = (linearlayout) Findviewbyid (R.id.password_uppercase_view); Passwordminuppercaseview.setvisibility (view.visible) (TextView) Findviewbyid (r.id.policy_password_ Uppercase)). SetText (String.valueof (Mpolicy.getpasswordminuppercase ()));}/** * Set navigation information/PRIV ate 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.layo
  Ut.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 (); Setscreenc Ontent (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 () {p          
   ublic void OnClick (view view) {startactivity (New Intent (View.getcontext (), Secureactivity.class));}
  }}/** * Listener implementation, this is not much to say. * Private View.Onclicklistener Mactivatebuttonlistener = new View.onclicklistener () {@Override public void OnClick (View v) {//Fi RST, persist the policy. Then, launch intent to trigger the system screens//requesting user to confirm the activation of the device Administrato R. Writepolicy (); Intent activatedeviceadminintent = new Intent (devicepolicymanager.action_add_device_admin); acti Vatedeviceadminintent.putextra (Devicepolicymanager.extra_device_admin, Mpolicy.getpolicyadmin ());//It is Good practice to include the optional explanation text to explain to//user why the application was requesting to be a D
  Evice Administrator.
  The System//would 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);};/** * Listener implementation, this smallAnd the horse said no more. * Private View.onclicklistener Menforcepolicylistener = new View.onclicklistener () {@Override public void OnClick ( View v) {writepolicy ()//The device administration API does not ' fix ' password if it is//determined that th E Current password does not conform to what are requested/by the policy.
  The caller is responsible to triggering the password set up//screen via the below intent. Intent Intent = new Intent (Devicepolicymanager.action_set_new_password); startactivity (Intent);}};/** * setting Activate Press  button different state text information * @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); //When this page is closed, the configuration information is written to the local SP file. private void Writepolicy () {int passwordquality = (int) mpasswordqualityinputfield.getselecteditemid (); int passwordl ength = 0; try {passwordlength = integer.valueof (Mpasswordlengthinputfield.gettext (). toString ()); \ catch (Numberfo
  Rmatexception 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);}

Configure action class:

Package com.xiaoma.policymanager.demo; import android.app.Activity; import android.app.admin.DeviceAdminReceiver; I Mport Android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; I mport android.content.Intent import android.content.SharedPreferences; import android.os.Build;/** * @Title: P Olicy.java * @Package Com.xiaoma.policymanager.demo * @Description: Class * @author Mzh/public class for obtaining relevant security configuration information Pol Icy {public static final int request_add_device_admin = 1;/** Save the SP filename for screen lock related parameters * * private static final String App_pre F = "App_pref";/** the following three are key*/private static final String key_password_length = "Pw_length" When they are stored in the SP; private static Final string key_password_quality = "pw_quality"; private static final String key_password_min_uppercase = "Pw_min_upper  Case "/** * below is a type that allows you to enter a password, which must match the type in the Arrays.xml defined in the string.xml file * * 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 mPas swordquality, private int mpasswordlength, private int mpasswordminuppercase, private context Mcontext, private De
  Vicepolicymanager MDPM Private ComponentName mpolicyadmin/** * constructor, get system-level administrator object when new such object Devicepolicymanager *  @param context * * 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);}/** * Save device parameters/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 (MP Asswordminuppercase! = passwordminuppercase) {editor.putint (key_password_min_uppercase, passwordminuppercase); mPasswordMinUpperCa
  SE = passwordminuppercase} editor.commit ();/** * Get password configuration parameters from local SP file/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 = pr
  Efs.getint (Key_password_min_uppercase,-1);}/** * Get the password. * * @return/public int GETpasswordquality () {return mpasswordquality;}/** * Gets the password length.
  * * @return/public int getpasswordlength () {return mpasswordlength;}/** * Get the letter password. * * @return/public int getpasswordminuppercase () {return mpasswordminuppercase;}/** * acquire Device Management Componentnam
  E object.
  * * @return/public componentname getpolicyadmin () {return mpolicyadmin;}/** * To determine whether the device is activated. * * @return/public boolean isadminactive () {return mdpm.isadminactive (mpolicyadmin);} public Boolean Isac Tivepasswordsufficient () {return mdpm.isactivepasswordsufficient ();}/** * Determine if the device is safe * @return/public b Oolean isdevicesecured () {return isadminactive () && Isactivep asswordsufficient ();}/** * in declared MDPM object
  Row configuration.
  */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);}/** * The following class is used to monitor a variety of different types of devices Manage events, such as: Change password wrong password and so on * * public static class Policyadmin extends Deviceadminreceiver {@Override public void ondisabl
  Ed (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);/** clears all values previously saved under the SP file */Prefs.edit (). Clear (). commit ();}}

Permission Validation class:

Package Com.xiaoma.policymanager.demo
Import android.app.Activity
import android.content.Intent;/
* *
* @Title: Secureactivity.java
* @Package Com.xiaoma.policymanager.demo *
@Description: Permission validation class implementation
* @ Author Mzh
*
/public class Secureactivity extends activity {
@Override
protected void Onresume () C12/>super.onresume ();
//Check to = If the device is properly secured as/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);
}

I hope this article will help you, Android to achieve screen lock source details of the content is introduced here. I hope you will continue to pay attention to our website! Want to learn Android can continue to focus on this site.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.