Android UserManager: Check if user is owner (admin)

后端 未结 3 1319
刺人心
刺人心 2020-12-31 12:55

Im developing an app with the latest android version (4.2.1 API-Level 17) for tablets with multiuser capabilities.

I want to restrict certain features (like the acce

3条回答
  •  暖寄归人
    2020-12-31 13:22

    You can create an extension property in Kotlin to make it simpler:

    val UserManager.isCurrentUserDeviceOwner: Boolean
        get() = if (SDK_INT >= 23) isSystemUser
        else if (SDK_INT >= 17) getSerialNumberForUser(Process.myUserHandle()) == 0L
        else true
    

    Then, using it is as simple as the following:

    val userManager = context.getSystemService(Context.USER_SERVICE) as UserManager
    if (userManager.isCurrentUserDeviceOwner) TODO() else TODO()
    

    You can further reduce boilerplate by using global system services definitions that makes userManager and other Android System Services available anywhere in your Kotlin code, with code included in this library I made: https://github.com/LouisCAD/Splitties/tree/master/systemservices

提交回复
热议问题