Tutorial #71: Implement lock screen in Android

In general, there are several ways to lock a screen. One can use the PowerManager class along with the WAKE_LOCK permission and provide a certain amount of time for the device to go to sleep. Reducing the screen brightness to zero can also help to automatically turn off the screen. Both these approaches may prove useful at times but what if you want to develop your own lock screen application? One can’t just keep reducing the screen brightness. To solve this, we could make our application run as an Administrator by providing device administration features at the system level.

Android provides the Device Administration API enabling developers to use the device management services and applications. In this tutorial, we will learn how to implement the lock screen functionality in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Launch Eclipse IDE and create a new Android application project called AndroidLockScreenDemo with package name com.example

Step 2: Create Activity class

Create a new Activity class called MyLockScreenActivity within the above package and add the following code!


package com.example;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MyLockScreenActivity extends Activity implements OnClickListener {

	private static final int ADMIN_INTENT = 15;
	private static final String description = "Sample Administrator description";
	private DevicePolicyManager mDevicePolicyManager; 
	private ComponentName mComponentName;  

	protected void onCreate(Bundle savedInstanceState) {
		mDevicePolicyManager = (DevicePolicyManager)getSystemService(  
		mComponentName = new ComponentName(this, MyAdminReceiver.class);  
		Button btnEnableAdmin = (Button) findViewById(R.id.btnEnable);
		Button btnDisableAdmin = (Button) findViewById(R.id.btnDisable);
		Button btnLock = (Button) findViewById(R.id.btnLock);

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnEnable:
			Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
			intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
			startActivityForResult(intent, ADMIN_INTENT);

		case R.id.btnDisable:
			Toast.makeText(getApplicationContext(), "Admin registration removed", Toast.LENGTH_SHORT).show();

		case R.id.btnLock:
			boolean isAdmin = mDevicePolicyManager.isAdminActive(mComponentName);  
			if (isAdmin) {  
				Toast.makeText(getApplicationContext(), "Not Registered as admin", Toast.LENGTH_SHORT).show();

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ADMIN_INTENT) {
			if (resultCode == RESULT_OK) {
				Toast.makeText(getApplicationContext(), "Registered As Admin", Toast.LENGTH_SHORT).show();
				Toast.makeText(getApplicationContext(), "Failed to register as Admin", Toast.LENGTH_SHORT).show();



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"






Step 3: Add lock policy and create receiver

Create a new folder called xml inside the project and add an XML file for exercising admin rights called admin.xml containing the following code!

<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
        <force-lock />

You also need to create an empty Receiver class that will extend the DeviceAdminReceiver. I am going to name my class as MyAdminReceiver.


package com.example;

import android.app.admin.DeviceAdminReceiver;

public class MyAdminReceiver extends DeviceAdminReceiver{


In this case, one needs to update the AndroidManifest.xml file and add the Receiver entry as follows!

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >

        android:targetSdkVersion="18" />

        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />


                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />


Save all changes and make sure no errors are present. Finally, run the application on an Android device and you should now be able to lock your screen through code! 🙂



Source code for this tutorial can be found over here

Karan Balkar About Karan Balkar
self proclaimed extraterrestrial fandroid, computer engineer, amateur gamer and die hard punk rock fan!

83 thoughts on “Tutorial #71: Implement lock screen in Android

  1. Pingback: Tutorial #71: Implement lock screen in Android - appgong

  2. My program didn’t work. There is no error but when i start the emulator it shows- “Unfortunately the program has stopped”. I also get an error ” Unknown Failure”

  3. Hi Karan,

    What i need to change in above code if i need to lock/unlock it using accelerometer? I tried to modify the code but all i get is a black screen.

  4. I want a button on lock screnn…
    Am nt getting if we already have a lock screen on android then why we are creating…?
    I want a button which will directly on tht lock screen….
    Bt need your help….plz tell me

  5. Guide me how to create admin.xml? by default it create in layout folder and which layout is to be choose. Attach any screen shot

  6. Hey. Thanks for the tutorial! One thing i want to know that how can i disable the home button on my activity in case of a lock screen? once i make my lock screen and deploy it, clicking on the home button automatically stops my activity and takes the user back to the home screen. Many apps on the play store can disable the home button. I did some research and found that once i set my app as the home screen laucher it is possible but cannot figure how exactly to do it. Your help will be greatly appreciated.

  7. Thanks for your tutorial. I have a question about the program. After I click the button to disable the admin registration, the device also can be locked by pressing the lock button. May I ask how to solve it? I am sorry for English and hope you can understand my meaning. Thanks again!

  8. Hi, Karan Balkar! Thanks your tutorial. When a user clicks the button to register as a admin, a dialog will be popped up. If the user selects to cancel this action, how can I change the content showing in Toast based on user’s selection? Thank you and hope for your reply!

  9. Thanx for your tutorial. this tutorial great pleaser for me.

    can u update your tutorial.
    it,s look,s like pretty old,
    you can update this tutorial like some photo security, useing some background image. or pattren .

    Afrer All thanx.

    i tried many times google for this type tutorial but i can.t find.

    finaly i find this. so many many thanx for this.

  10. Where have you created the xml file ? I am using Android Studio as my development environment so it is showing compiler error with the xml file as I have created it in values folder under res directory

    • there is an button in android studio where you can choose project, package,scartches , android,project files etc. so go to project there and then go to app –> src–> main –> res . then make new XML directory and there add a xml file called admin.xml

  11. i have condition if it gets true i want to unlock the phone else display err message! can u tell me the way out.
    i dont know how to take permit and device admin stuff.

  12. This worked well. Only thing is when I press LOCK Button, screen locking sound appress twice. Why does it happen, ideally it should happen only ones.

  13. Hi
    I want to develop an app that if I enter wrong password it take a selfie of person and stores in phone.
    A user can change password and turn this security off and on can u please help me regards this?

  14. i have tried this code, but having problem in the gradle part. like following

    Error:Failed to complete Gradle execution.

    C:\Program Files\Android\Android Studio\gradle\gradle-2.8\native\jna\win32-amd64\jnidispatch.dll (The system cannot find the path specified)

    please help

  15. Two errors got
    2.debug\Android Manifest.xml
    <instrumentation …..
    what should I do? ?help plz

Leave a Reply

Your email address will not be published. Required fields are marked *