Android Working with Lock Screen and Device Administration API

Device Administration API is an amazing administration feature at the system level which allows to create security applications that are useful in rich control over devices and settings that are powered by Android. Almost all Security Android Application such as Avast! Mobile SecurityAvira Antivirus SecurityLookout Security & Antivirus etc. depending on the permissions and feature provided under Android Device Administration API. Android Device Manager is a Google app that also uses device administration API which allows to track and secure devices remotely and perform many other operations like Erase Data, Change Screen-Unlock Password as well as Lock the screen.

In this tutorials, we’ll learn how to implement android application working with the Lock screen and Device Administration API. So we will add some features in this application that will detect the wrong attempt of password or pattern lock on your device. If password attempt is right then toast will appear “welcome Device Owner” and on wrong attempt, your mobile will Vibrate.

Float News
Float News
Developer: Ashok Purohit
Price: To be announced

   DOWNLOAD CODE   

Creating Android Project:

Refer Android beginners app development guide if you are a beginner or if you don’t know how to create project in android studio.

1. In Android Studio, create a new project

  • If you don’t have a project opened, in the Welcome screen, click New Project.
  • If you have a project opened, from the File menu, select New Project.

2. Under Configure your new project, fill  the following fields as given below

  • Application Name ⇒ Lockscreen-Monitor
  • Company domain ⇒ example.com ( Eg: gadgetcreek.com)
  • Project location ⇒ choose a location for your project.

3. Under Select, the form factors your app will run on, check the box for Phone and Tablet.

4. For Minimum SDK, select API 10: Android 2.3.3 (Gingerbread). click Next.

5. Under Add an activity to Mobile, select Empty Activity and click Next.

6. Click the Finish button to create the project.

7. Select your View as Project, Open the layout file for main activity(activity_main.xml) located under src/main/res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.gadgetcreek.lockscreen_monitor.MainActivity">

    <TextView
        android:text="@string/gc"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt1"
        android:layout_marginTop="40dp"
        android:layout_margin="30dp"
        android:textSize="30sp"
        android:gravity="center_horizontal"
        android:textColor="@color/gc"/>

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switchButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:checked="false"
        android:layout_centerInParent="true"
        android:text="@string/app_name"
        android:textOff="@string/off"
        android:textOn="@string/on"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="25sp"
        app:showText="true"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_margin="16dp"
        app:srcCompat="@android:drawable/ic_lock_idle_lock" />

</RelativeLayout>

Open build.gradle and add design support library dependency (located under  app/build.gradle)

com.android.support:appcompat-v7:25.1.1 and com.android.support:design:25.1.1

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.gadgetcreek.lockscreen_monitor"
        minSdkVersion 9
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support:design:25.1.1'
    testCompile 'junit:junit:4.12'
}

Following is the content of the res/values/strings.xml.

<resources>
    <string name="app_name">Lockscreen-Monitor</string>
    <string name="gc">Gadget Creek</string>
    <string name="on">ON</string>
    <string name="off">OFF</string>
</resources>

and res/values/colors.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="gc">#009871</color>
</resources>

also res/values/dimens.xml.

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>

8. Now Open the MainActivity.java file located under src/main/Java/MainActivity.java and add below code.

package com.gadgetcreek.lockscreen_monitor;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final int ADMIN_INTENT = 1;
    private DevicePolicyManager mDevicePolicyManager;
    private ComponentName mComponentName;
    private FloatingActionButton fab;
    SwitchCompat switchCompat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDevicePolicyManager = (DevicePolicyManager)getSystemService(
                Context.DEVICE_POLICY_SERVICE);
        mComponentName = new ComponentName(this, Admin.class);
        switchCompat=(SwitchCompat)findViewById(R.id.switchButton);

        if( mDevicePolicyManager != null && mDevicePolicyManager.isAdminActive(mComponentName)) {
            switchCompat.setChecked(true);
        }

        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if ((switchCompat).isChecked()) {
                    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
                    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Administrator description");
                    startActivityForResult(intent, ADMIN_INTENT);
                }
                else {
                    mDevicePolicyManager.removeActiveAdmin(mComponentName);
                }

            }
        });

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isAdmin = mDevicePolicyManager.isAdminActive(mComponentName);
                if (isAdmin) {
                    mDevicePolicyManager.lockNow();
                }else {
                    Snackbar snackbar = Snackbar.make(view, "Turn ON Lockscreen Monitor", Snackbar.LENGTH_LONG);
                    snackbar.show();
                }
            }
        });
    }

    @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(), "Device Administrator Process Cancelled", Toast.LENGTH_SHORT).show();
                switchCompat.setChecked(false);
            }
        }
    }
}

Create a new Java Class file under src/main/Java called Admin.Java and that will extend the DeviceAdminReceiver. Add the following below code to Admin.Java.

package com.gadgetcreek.lockscreen_monitor;

import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;

public class Admin extends DeviceAdminReceiver {

    void showToast(Context context, CharSequence msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onEnabled(Context context, Intent intent) {
        showToast(context, "Device Administrator: Activated");
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        return "This is an optional message to warn the user about disabling.";
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        showToast(context, "Device Administrator: Deactivated");
    }

    @Override
    public void onPasswordFailed(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: pw failed");
        Vibrator v = (Vibrator)context.getSystemService(context.VIBRATOR_SERVICE);
        // Vibrate for 2 seconds
        v.vibrate(2000);
    }

    @Override
    public void onPasswordSucceeded(Context context, Intent intent) {
        showToast(context, "Welcome Device Owner");
    }
}

On wrong attempt of password the phone will vibrate for 2 seconds and correct password will generate Toast as Welcome Device Owner.

9. Create a new subfolder called xml inside the folder res and create or add an XML file for exercising admin rights called admin.xml containing the following code!

(res/xml/admin.xml)

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

This xml code will Add following operations like

  • <watch-login /> → Monitor Screen-Unlock attempts.
  • <force-lock /> → Lock the screen

10. Checkout how Project and File Structure will look.

folder structure lockscreen-monitor

11. Finally, open your AndroidManifest.xml. located under app/src. and add the VIBRATE permission as we need to make vibration calls on wrong attempt password from the Lock screen.

To use the Device Administration API, the application’s manifest must include the following:

Add the following code to manifest file, this is how your manifest file should look like.

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

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".Admin"
            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>

With this, we have completed coding work of Lock screen and Device Administration API android application. To run the app from Android studio, click Run icon Eclipse Run Icon from the toolbar.

Please comment below with any questions or doubt.

Sending
User Review
4.5 (2 votes)

3 thoughts on “Android Working with Lock Screen and Device Administration API”

  1. I love your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to create my own blog and would like to know where u got this from. thank you|

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.