Lock Screen on Power Button Failure

The power button is gone on my outdated Google Pixel. In need of function to lock screen via a single touch, there it is

Lock Screen on Power Button Failure
Photo by Franck / Unsplash

There is no single permission grant for performing a screen lock action

by Claude

Key Component

DeviceAdminReceiver

MyDeviceAdminReceiver.kt

class MyDeviceAdminReceiver : DeviceAdminReceiver() {
    override fun onEnabled(context: Context, intent: Intent) {
        super.onEnabled(context, intent)
        // Device admin has been enabled
    }

    override fun onDisabled(context: Context, intent: Intent) {
        super.onDisabled(context, intent)
        // Device admin has been disabled
    }

    override fun onPasswordChanged(context: Context, intent: Intent) {
        super.onPasswordChanged(context, intent)
        // Device password has been changed
    }
}

declare it in AndroidManifest

AndroidManifest.xml

<receiver
    android:name=".MyDeviceAdminReceiver"
    android:permission="android.permission.BIND_DEVICE_ADMIN"
    android:exported="true">
    <meta-data
        android:name="android.app.device_admin"
        android:resource="@xml/device_admin_policies" />
    <intent-filter>
        <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
    </intent-filter>
</receiver>

specify the policy

device_admin_policies.xml

<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <force-lock />
        <wipe-data />
        <reset-password />
    </uses-policies>
</device-admin>

provide a way to activate the device admin features

MainActivity

val deviceAdmin = ComponentName(this, MyDeviceAdminReceiver::class.java)
val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin)
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Explanation for why this admin is needed")
startActivity(intent)