[Android device management] uses devicepolicymanager to lock the screen

Source: Internet
Author: User

Generally, when an Android phone is not used, it uses the power key to lock the screen and turn off the screen light.

 

In fact, from API Level 8 (Android 2.2), Android provides the devicepolicymanager class, allowing your application to perform screen lock and other operations.

 

Lock effect:

 

 

Next, let's take a look at the specific operations. To lock your application to the screen, you need to use the following categories:

 

 

Devicepolicymanager

This is the main category of device management. It enables screen locking, screen brightness adjustment, factory settings, and other functions.

 

 

Deviceadminreceiver

 

This class inherits from broadcastreceiver. From the source code, we can see that an onreceive method is actually implemented. This method performs corresponding operations based on different actions. For example, if activation is successful, action is action_device_admin_enabled, And the onenabled method is called accordingly.

 

System source code:

/** <Br/> * intercept standard device administrator broadcasts. implementations <br/> * shocould not override this method; it is better to implement the <br/> * convenience callbacks for each action. <br/> */<br/> @ override <br/> Public void onreceive (context, intent) {<br/> string action = intent. getaction (); <br/> If (action_password_changed.equals (Action) {<br/> onpasswordchange D (context, intent); <br/>} else if (action_password_failed.equals (Action) {<br/> onpasswordfailed (context, intent ); <br/>} else if (Response (Action) {<br/> onpasswordsucceeded (context, intent); <br/>} else if (action_device_admin_enabled.equals (Action )) {<br/> onenabled (context, intent); <br/>} else if (action_device_admin_disable_requested.equals (Action) {<br/> Charsequence res = ondisablerequested (context, intent); <br/> If (res! = NULL) {<br/> bundle extras = getresultextras (true); <br/> extras. putcharsequence (extra_disable_warning, Res); <br/>}< br/>} else if (action_device_admin_disabled.equals (Action) {<br/> ondisabled (context, intent ); <br/>}< br/>} 

 

Deviceadmininfo

Define the meta information of the device management class. What does it mean? Defines available permissions. Define policy that this device admin can use.

 

 

For example, deviceadminreceiver. uses_policy_force_lock is the "Force lock screen" permission used this time. However, these permissions are generally defined in XML files. You will see it later.

 

 

 

 

Next we will look at how to implement screen lock.

Note: The screen lock mentioned here is actually the locking method of the called system.

In "Settings"-"location and security"-"change screen lock", you can set a locking method. There are four types:

1. No lock

2. Pattern lock (that is, the jiugong figure)

3. pin lock

4. password lock

 

Which lock is set on your mobile phone and will be displayed when you call this API!

 

(Lock type setting screen)

 

 

 

Step 1: Write a layout file with four buttons, corresponding to "Activate device management Permissions", "Disable device management Permissions", "system lock", and "Custom lock ".

The "Custom lock" is described in the next blog. This time is not required.

 

The layout file is as follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <relativelayout <br/> xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: gravity = "center" <br/> Android: id = "@ + ID/rltextdescblock" <br/> Android: layout_width = "wrap_content" <br/> Android: layout_height = "wrap_content"> <br/> <linearlayout <br/> Android: Id = "@ + ID/layout1" <br/> Android: orientation = "horizontal" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: layout_margintop = "30px"> <br/> <button <br/> Android: Id = "@ + ID/active" <br/> Android: textsize = "14.0sp" <br/> Android: textstyle = "bold" <br/> Android: textcolor = "# ff5779a7" <br/> Android: background = "@ drawable/detail_redirect_button_bg" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: layout_marginleft = "10.0dip" <br/> Android: text = "Activate" <br/> Android: layout_weight = "1.0"/> <br/> <button <br/> Android: Id = "@ + ID/unactive" <br/> Android: textsize = "14.0sp" <br/> Android: textstyle = "bold" <br/> Android: textcolor = "# ff5779a7" <br/> Android: background = "@ drawable/detail_comment_button_bg" <br/> Android: paddingright = "10.0dip" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: layout_marginright = "10.0dip" <br/> Android: text = "disabled" <br/> Android: layout_weight = "1.0"/> <br/> </linearlayout> </P> <p> <linearlayout <br/> Android: layout_below = "@ ID/layout1" <br/> Android: Orientation = "horizontal" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: layout_margintop = "30px"> <br/> <button <br/> Android: id = "@ + ID/syslock" <br/> Android: textsize = "14.0sp" <br/> Android: textstyle = "bold" <br/> Android: textcolor = "# ff5779a7" <br/> Android: Background = "@ drawable/detail_redirect_button_bg" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: layout_marginleft = "10.0dip" <br/> Android: text = "" <br/> Android: layout_weight = "1.0"/> <br/> <button <br/> Android: Id = "@ + ID/custlock" <br/> Android: textsize = "14.0sp" <br/> Android: textstyle = "bold" <br/> Android: textcolor = "# ff5779a7" <br/> Android: background = "@ drawable/detail_comment_button_bg" <br/> Android: paddingright = "10.0dip" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: layout_marginright = "10.0dip" <br/> Android: text = "Custom lock screen" <br/> Android: layout_weight = "1.0" type = "codeph" text = "codeph"/> <br/> </linearlayout> <br/> </relativelayout> 

 

:

 

 

 

The following are the corresponding implementation functions.

 

1. "Activate.

 

Step 1: Initialize several types of device management:

// Obtain the device management service <br/> policymanager = (devicepolicymanager) getsystemservice (context. device_policy_service); </P> <p> // adminreceiver inherits from deviceadminreceiver <br/> componentname = new componentname (this, adminreceiver. class );

 

The code of the admincycler class is as follows:

Package COM. yfz. broadcast; <br/> Import COM. yfz. log. logger; <br/> Import android. app. admin. deviceadmininfo; <br/> Import android. app. admin. deviceadminreceiver; <br/> Import android. app. admin. devicepolicymanager; <br/> Import android. content. componentname; <br/> Import android. content. context; <br/> Import android. content. intent; <br/> Import android. content. PM. resolveinfo; <br/> Import android. OS. ibinder; <br/> Import android. widget. toast; <br/> public class adminreceiver extends deviceadminreceiver {<br/> @ override <br/> Public devicepolicymanager getmanager (context) {<br/> logger. D ("------" + "getmanager" + "------"); <br/> return Super. getmanager (context); <br/>}< br/> @ override <br/> Public componentname getwho (context) {<br/> logger. D ("------" + "getwho" + "------"); <br/> return Super. getwho (context ); <br/>}</P> <p>/** <br/> * disable <br/> */<br/> @ override <br/> Public void ondisabled (context, intent intent) {<br/> logger. D ("------" + "ondisabled" + "------"); </P> <p> toast. maketext (context, "Disable device management", toast. length_short ). show (); </P> <p> super. ondisabled (context, intent); <br/>}< br/> @ override <br/> Public charsequence ondisablerequested (context, intent) {<br/> logger. D ("------" + "ondisablerequested" + "------"); <br/> return Super. ondisablerequested (context, intent ); <br/>}</P> <p>/** <br/> * activate <br/> */<br/> @ override <br/> Public void onenabled (context, intent intent) {<br/> logger. D ("------" + "onenabled" + "------"); </P> <p> toast. maketext (context, "start device management", toast. length_short ). show (); </P> <p> super. onenabled (context, intent); <br/>}< br/> @ override <br/> Public void onpasswordchanged (context, intent) {<br/> logger. D ("------" + "onpasswordchanged" + "------"); <br/> super. onpasswordchanged (context, intent); <br/>}< br/> @ override <br/> Public void onpasswordfailed (context, intent) {<br/> logger. D ("------" + "onpasswordfailed" + "------"); <br/> super. onpasswordfailed (context, intent); <br/>}< br/> @ override <br/> Public void onpasswordsucceeded (context, intent) {<br/> logger. D ("------" + "onpasswordsucceeded" + "------"); <br/> super. onpasswordsucceeded (context, intent); <br/>}< br/> @ override <br/> Public void onreceive (context, intent) {<br/> logger. D ("------" + "onreceive" + "------"); </P> <p> super. onreceive (context, intent); <br/>}< br/> @ override <br/> Public ibinder peekservice (context mycontext, intent Service) {<br/> logger. D ("------" + "peekservice" + "------"); <br/> return Super. peekservice (mycontext, service); <br/>}</P> <p >}< br/> 

 

It inherits the deviceadminreceiver and does not perform any special operations. It only outputs a prompt message when it is excited or disabled.

In addition, like the normal broadcast class, this class also needs to be registered in the androidmanifest. xml file.

As follows:

<! -- Device management --> <br/> <explorer Android: Name = ". broadcast. adminreceiver "<br/> Android: Label =" @ string/device "<br/> Android: Description =" @ string/device_des "<br/> Android: permission = "android. permission. bind_device_admin "> <br/> <meta-data Android: Name =" android. app. device_admin "<br/> Android: Resource =" @ XML/lock_screen "/> <br/> <intent-filter> <br/> <action <br/> Android: name = "android. app. action. device_admin_enabled "/> <br/> </intent-filter> <br/> </receiver> 

 

Where

Android: Permission = "android. Permission. bind_device_admin" and

 

<Intent-filter>

<Action Android: Name = "android. App. Action. device_admin_enabled"/>

</Intent-filter>

 

Is required.

 

Android: Resource = "@ XML/lock_screen" corresponds to the permission description file.

This time, you only need to force lock the permission. As follows:

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <device-Admin <br/> xmlns: Android = "http://schemas.android.com/apk/res/android"> <br/> <uses-policies> <br/> <! -- Force lock --> <br/> <force-Lock/> <br/> </uses-policies> <br/> </device-Admin> <br/> 

 

 

Step 2: run the Code with the "Activate" button:

 

/** <Br/> * activate the device management permission <br/>, onenabled in deviceadminreceiver will respond to <br/> */<br/> private void activemanage () {<br/> // start device management (implicit intent)-In androidmanifest. set the corresponding filter in XML <br/> intent = new intent (devicepolicymanager. action_add_device_admin); </P> <p> // permission list <br/> intent. putextra (devicepolicymanager. extra_device_admin, componentname); </P> <p> // description (additional explanation) <br/> intent. putextra (devicepolicymanager. extra_add_explanation, "------ other descriptions ------"); </P> <p> startactivityforresult (intent, 0); <br/>} 

 

Here, an implicit intent is used to jump to the Permission Notification page through this intent (devicepolicymanager. action_add_device_admin. Two Parameters extra_device_admin and extra_add_explanation are also passed.

The extra_device_admin parameter describes the permissions used. The extra_add_explanation parameter is an additional description.

 

In this way, an activation function is complete. The activation page is as follows:

 

 

"Device management software description: we are not hackers, please rest assured! "Android: Description =" @ string/device_des "in the androidmanifest. xml file ".

 

"------ Other descriptions ------" is the prepaid extra_add_explanation parameter.

 

I personally think it is okay to have one and I don't know why to provide two.

 

Step 3: click "Activate ".

The application has the permission to manage devices. The onenabled method of the admincycler class is called when it is activated.

 

2. "Disable.

 

If "Activate" is selected, you can continue to use these permissions without re-activating them. But what should I do if I want to "Disable?

The answer is simple. You just need to call the following method.

/** <Br/> * disable the device management permission <br/> * when the device is disabled successfully, the ondisabled in deviceadminreceiver will respond to <br/> */<br/> private void unactivemanage () {<br/> logger. D ("------ unactivemanage ------"); <br/> Boolean active = policymanager. isadminactive (componentname); <br/> If (active) {<br/> policymanager. removeactiveadmin (componentname); <br/>}< br/>} 

 

When it is disabled, the ondisabled method of the admincycler class will be called.

 

3. "system lock"

In fact, this is already very simple. All configuration and initialization are done during activation.

The following code calls the system lock directly:

Boolean active = policymanager. isadminactive (componentname); <br/> If (active) {<br/> policymanager. locknow (); <br/>}

 

So far, the screen lock has ended.

 

The code for the main classes is attached:

Package COM. yfz; <br/> Import COM. yfz. broadcast. adminreceiver; <br/> Import COM. yfz. log. logger; <br/> Import android. app. activity; <br/> Import android. app. activitymanager; <br/> Import android. app. alertdialog; <br/> Import android. app. admin. devicepolicymanager; <br/> Import android. content. componentname; <br/> Import android. content. context; <br/> Import android. content. intent; <br/> Import android. OS. bundle; <br/> Import android. view. view; <br/> Import android. view. view. onclicklistener; <br/> Import android. widget. button; <br/> public class lesson13 extends activity implements onclicklistener {</P> <p> private devicepolicymanager policymanager; <br/> private componentname; </P> <p> @ override <br/> protected void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. lesson13); </P> <p> // obtain the device management service <br/> policymanager = (devicepolicymanager) getsystemservice (context. device_policy_service); </P> <p> // adminreceiver inherits from deviceadminreceiver <br/> componentname = new componentname (this, adminreceiver. class); </P> <p> Init (); <br/>}< br/> private void Init () {<br/> button active = (button) findviewbyid (R. id. active); <br/> button unactive = (button) findviewbyid (R. id. unactive); <br/> button syslock = (button) findviewbyid (R. id. syslock); </P> <p> active. setonclicklistener (this); <br/> unactive. setonclicklistener (this); <br/> syslock. setonclicklistener (this); <br/>}< br/> @ override <br/> Public void onclick (view v) {<br/> switch (v. GETID () {<br/> case R. id. active: <br/> activemanage (); <br/> break; <br/> case R. id. unactive: <br/> unactivemanage (); <br/> break; <br/> case R. id. syslock: <br/> systemlock (); <br/> break; <br/> default: <br/> break; <br/>}</P> <p>/** <br/> * activate the device management permission <br/> * when the device is activated successfully, onenabled in deviceadminreceiver will respond to <br/> */<br/> private void activemanage () {<br/> // start device management (implicit intent)-In androidmanifest. set the corresponding filter in XML <br/> intent = new intent (devicepolicymanager. action_add_device_admin); </P> <p> // permission list <br/> intent. putextra (devicepolicymanager. extra_device_admin, componentname); </P> <p> // description (additional explanation) <br/> intent. putextra (devicepolicymanager. extra_add_explanation, "------ other descriptions ------"); </P> <p> startactivityforresult (intent, 0 ); <br/>}</P> <p>/** <br/> * disable the device management permission. <br/> * if the device is disabled successfully, the ondisabled in deviceadminreceiver will respond to <br/> */<br/> private void unactivemanage () {<br/> logger. D ("------ unactivemanage ------"); <br/> Boolean active = policymanager. isadminactive (componentname); <br/> If (active) {<br/> policymanager. removeactiveadmin (componentname ); <br/>}</P> <p>/** <br/> * call up the system lock <br/> */<br/> private void systemlock () {<br/> logger. D ("------ lock screen ------"); <br/> Boolean active = policymanager. isadminactive (componentname); <br/> If (active) {<br/> policymanager. locknow (); <br/>}< br/>} 

 

 

Finally, there are five permissions for device management.

See the description in the configuration file.

 <? XML version = "1.0" encoding = "UTF-8"?> <Br/> <device-Admin <br/> xmlns: Android = "http://schemas.android.com/apk/res/android"> <br/> <uses-policies> <br/> <! -- Force lock --> <br/> <force-Lock/> <br/> <! -- Clear all data (Restore factory settings) --> <br/> <wipe-data/> <br/> <! -- Reset Password --> <br/> <reset-Password/> <br/> <! -- Restrict password selection --> <br/> <limit-Password/> <br/> <! -- Monitor logon attempt --> <br/> <watch-login/> <br/> </uses-policies> <br/> </device-Admin> <br/> 

 

When all permissions are applied:

 

 

 

The Force screen lock function can be applied to some security software, such as mobile phone security guard. When a mobile phone is lost, the user sends a command text message or email to the mobile phone to force the mobile phone to lock the screen. In this case, it cannot be used if someone else finds it in time.

 

However, mobile phone users may not necessarily set the mobile phone lock, so calling the system lock may not be very useful. Therefore, we will create a custom lock in the next article, which will only be enabled as needed.

 

Related Article

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.