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!

MyLockScreenActivity.java

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;  

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lock);
		mDevicePolicyManager = (DevicePolicyManager)getSystemService(  
				Context.DEVICE_POLICY_SERVICE);  
		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);
		btnEnableAdmin.setOnClickListener(this);
		btnDisableAdmin.setOnClickListener(this);
		btnLock.setOnClickListener(this);
	}

	@Override
	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);
			intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,description);
			startActivityForResult(intent, ADMIN_INTENT);
			break;

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

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

	@Override
	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();
			}else{
				Toast.makeText(getApplicationContext(), "Failed to register as Admin", Toast.LENGTH_SHORT).show();
			}
		}
	}

}

activity_lock.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyLockScreenActivity">

    <TextView
        android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"/>

    <Button
        android:id="@+id/btnEnable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enable"
        android:layout_below="@+id/txt1"/>

    <Button
        android:id="@+id/btnDisable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Disable"
        android:layout_below="@+id/btnEnable"/>

    <Button
        android:id="@+id/btnLock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lock"
        android:layout_below="@+id/btnDisable"/>

</RelativeLayout>

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" >
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

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

MyAdminReceiver.java

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"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MyLockScreenActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="MyAdminReceiver"
            android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/admin"/>

            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filter>
        </receiver>
        
    </application>

</manifest>

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! 🙂

lock_screen_1

lock_screen_2

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.

    Cause:
    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
    1.main\AndroidMainfest.xml
    <activity
    android:name="com.example.white_hat.screenlock.MyLockScreenActivity"
    2.debug\Android Manifest.xml
    <instrumentation …..
    android:targetPackage="com.example.white_hat.screenlock"
    what should I do? ?help plz

Leave a Reply

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