I am a beginner in Android. I am trying to make an app that can switch the user between the primary and secondary without root.
I found DevicePolicyManager.switchUser useful in my case.
So I granted my app device owner privilege with adb. When the app is launched in the primary user, it switch to the secondary user without problem.
However, when the app is launched in the secondary user, it can no longer switch back to the primary user by invoking dpm.switchUser(admin, null)
, because admin
is not a device owner, which throws a SecurityException.
I'd like to know the workaround of this problem. Thank you.
private fun switchUser() {
dpm = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
admin = ComponentName(applicationContext, DevAdmRcvr::class.java)
// If device admin not active, take user to settings
if (!dpm.isAdminActive(admin)) {
val activateDeviceAdminIntent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
activateDeviceAdminIntent.putExtra(
DevicePolicyManager.EXTRA_DEVICE_ADMIN,
admin
)
activateDeviceAdminIntent.putExtra(
DevicePolicyManager.EXTRA_ADD_EXPLANATION,
resources.getString(R.string.device_admin_activation_message)
)
startActivityForResult(activateDeviceAdminIntent, 1)
return
}
if (dpm.isDeviceOwnerApp(admin.packageName)) { // Return false if app run as secondary user
val secondaryUsers = dpm.getSecondaryUsers(admin)
if (secondaryUsers.isNotEmpty()) { // Switch to secondary user
Log.i(TAG, "Switch to secondary")
dpm.switchUser(admin, secondaryUsers[0])
} else { // Create and switch to new user
Log.i(TAG, "Create new")
val identifiers = dpm.getAffiliationIds(admin)
if (identifiers.isEmpty()) {
identifiers.add(UUID.randomUUID().toString())
dpm.setAffiliationIds(admin, identifiers)
}
val adminExtras = PersistableBundle()
adminExtras.putString("AFFILIATION_ID_KEY", identifiers.first())
try {
val newUser = dpm.createAndManageUser(
admin,
"Foo",
admin,
adminExtras,
DevicePolicyManager.SKIP_SETUP_WIZARD
)
dpm.switchUser(admin, newUser)
} catch (e: Exception) {
Toast.makeText(applicationContext, R.string.creation_failed, Toast.LENGTH_SHORT)
.show()
}
}
}
}