Skip to content

Instantly share code, notes, and snippets.

@NielsMasdorp
Created October 17, 2018 09:30
Show Gist options
  • Save NielsMasdorp/e97daa8687f6ee19d253c1a7d41e606a to your computer and use it in GitHub Desktop.
Save NielsMasdorp/e97daa8687f6ee19d253c1a7d41e606a to your computer and use it in GitHub Desktop.
Use Kiosk mode in Android to lock a single app

Add a admin receiver to your project

class AdminReceiver: DeviceAdminReceiver()

Add the receiver to the AndroidManifest.xml

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

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

With a provided device_admin.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <limit-password />
        <watch-login />
        <reset-password />
        <force-lock />
        <wipe-data />
    </uses-policies>
</device-admin>

Make sure the first launching Activity is set as a home launcher in AndroidManifest.xml

<activity
  android:name=".FirstActivity" >
    <intent-filter>
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.HOME" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Connect device and set app as device owner via adb

adb shell
dpm set-device-owner com.your.package_name/.AdminReceiver

For the FirstActivity inside the onCreate initialize kiosk mode

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  val myDevicePolicyManager = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
  val mDPM = ComponentName(this, AdminReceiver::class.java)
  if (myDevicePolicyManager.isDeviceOwnerApp(this.packageName)) {
    val packages = arrayOf(this.packageName)
    myDevicePolicyManager.setLockTaskPackages(mDPM, packages)
    startLockTask()
  } else {
    Toast.makeText(applicationContext, "Not device owner", Toast.LENGTH_LONG).show()
  }
}

Reboot the phone and set your app as launcher

Done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment