Install app as a device administrator

The following instructs how to set an app as a device admin. This can be useful for several things, mostly for running an app in kiosk mode. Being a device admin enables such an app to pin the screen, to prevent the lock screen, and prevents it from being uninstalled by the user without permission from the app.

Note that device administration functions are deprecated, and will be removed from Android soon. Also note that it is ineffective on Wear OS.

BroadcastReceiver

Include a BroadcastReceiver that takes care of being an admin, like so:

package com.pixplicity.example
import android.app.admin.DeviceAdminReceiver
import android.content.ComponentName
import android.content.Context

class ExampleDeviceAdminReceiver : DeviceAdminReceiver() {
    companion object {
        fun getComponentName(context: Context): ComponentName {
            return ComponentName(context.applicationContext, KotlinDeviceAdminReceiver::class.java)
        }
    }
}

Manifest

Add the following inside the <application> tag:

<receiver
    android:name=".NSDeviceAdminReceiver"
    android:description="@string/app_name"
    android:label="@string/app_name"
    android:permission="android.permission.BIND_DEVICE_ADMIN">
    <meta-data
        android:name="android.app.device_admin"
        android:resource="@xml/device_admin_receiver" />
    <intent-filter>
        <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
    </intent-filter>
</receiver>

and add this file to the res/xml/ folder of your module:

<?xml version="1.0" encoding="utf-8"?>
<device-admin>
    <uses-policies>
        <limit-password />
        <watch-login />
        <reset-password />
        <force-lock />
        <wipe-data />
        <expire-password />
        <encrypted-storage />
        <disable-camera />
        <disable-keyguard-features />
    </uses-policies>
</device-admin>

Remove the privileges you are not interested in.

Installation

First, you might want to use these instructions to install your app as a system app on an emulator or rooted device, but it is not necessarily needed. You may also install the app using simple adb install.

After installation, enable admin mode like so:

adb shell dpm set-device-owner com.pixplicity.example/com.pixplicity.example.ExampleDeviceAdminReceiver