Fix user switching race condition on boot
With HSUM, a switch is done immediately on boot to the main
user. This can occur as SystemUI is being initialized, leading
it to miss the "onUserSwitching" event, which performs critical
setup for the upcoming user.
If a switch is in progress during boot, manually send that event.
Also, fix a crash in the contentprovider during this user switch.
Fixes: 365707550
Test: atest UserTrackerImplTest
Test: manual - setup multiple users, one with security NONE, reboot
Flag: EXEMPT bugfix
Change-Id: Idf1403f7115c07c20c0514beb89af554aeb7bbc8
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
index 5a6c821..22130f8 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -2489,6 +2489,12 @@
this::onTransitionStateChanged
);
}
+
+ // start() can be invoked in the middle of user switching, so check for this state and issue
+ // the call manually as that important event was missed.
+ if (mUserTracker.isUserSwitching()) {
+ handleUserSwitching(mUserTracker.getUserId(), () -> {});
+ }
}
@VisibleForTesting
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/CustomizationProvider.kt b/packages/SystemUI/src/com/android/systemui/keyguard/CustomizationProvider.kt
index 342325f..6df8355 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/CustomizationProvider.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/CustomizationProvider.kt
@@ -54,29 +54,25 @@
addURI(
Contract.AUTHORITY,
Contract.LockScreenQuickAffordances.qualifiedTablePath(
- Contract.LockScreenQuickAffordances.SlotTable.TABLE_NAME,
+ Contract.LockScreenQuickAffordances.SlotTable.TABLE_NAME
),
MATCH_CODE_ALL_SLOTS,
)
addURI(
Contract.AUTHORITY,
Contract.LockScreenQuickAffordances.qualifiedTablePath(
- Contract.LockScreenQuickAffordances.AffordanceTable.TABLE_NAME,
+ Contract.LockScreenQuickAffordances.AffordanceTable.TABLE_NAME
),
MATCH_CODE_ALL_AFFORDANCES,
)
addURI(
Contract.AUTHORITY,
Contract.LockScreenQuickAffordances.qualifiedTablePath(
- Contract.LockScreenQuickAffordances.SelectionTable.TABLE_NAME,
+ Contract.LockScreenQuickAffordances.SelectionTable.TABLE_NAME
),
MATCH_CODE_ALL_SELECTIONS,
)
- addURI(
- Contract.AUTHORITY,
- Contract.FlagsTable.TABLE_NAME,
- MATCH_CODE_ALL_FLAGS,
- )
+ addURI(Contract.AUTHORITY, Contract.FlagsTable.TABLE_NAME, MATCH_CODE_ALL_FLAGS)
}
override fun onCreate(): Boolean {
@@ -106,15 +102,15 @@
when (uriMatcher.match(uri)) {
MATCH_CODE_ALL_SLOTS ->
Contract.LockScreenQuickAffordances.qualifiedTablePath(
- Contract.LockScreenQuickAffordances.SlotTable.TABLE_NAME,
+ Contract.LockScreenQuickAffordances.SlotTable.TABLE_NAME
)
MATCH_CODE_ALL_AFFORDANCES ->
Contract.LockScreenQuickAffordances.qualifiedTablePath(
- Contract.LockScreenQuickAffordances.AffordanceTable.TABLE_NAME,
+ Contract.LockScreenQuickAffordances.AffordanceTable.TABLE_NAME
)
MATCH_CODE_ALL_SELECTIONS ->
Contract.LockScreenQuickAffordances.qualifiedTablePath(
- Contract.LockScreenQuickAffordances.SelectionTable.TABLE_NAME,
+ Contract.LockScreenQuickAffordances.SelectionTable.TABLE_NAME
)
MATCH_CODE_ALL_FLAGS -> Contract.FlagsTable.TABLE_NAME
else -> null
@@ -128,6 +124,7 @@
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
+ if (!::mainDispatcher.isInitialized) return null
if (uriMatcher.match(uri) != MATCH_CODE_ALL_SELECTIONS) {
throw UnsupportedOperationException()
}
@@ -142,6 +139,7 @@
selectionArgs: Array<out String>?,
sortOrder: String?,
): Cursor? {
+ if (!::mainDispatcher.isInitialized) return null
return runBlocking("$TAG#query", mainDispatcher) {
when (uriMatcher.match(uri)) {
MATCH_CODE_ALL_AFFORDANCES -> queryAffordances()
@@ -163,11 +161,8 @@
return 0
}
- override fun delete(
- uri: Uri,
- selection: String?,
- selectionArgs: Array<out String>?,
- ): Int {
+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
+ if (!::mainDispatcher.isInitialized) return 0
if (uriMatcher.match(uri) != MATCH_CODE_ALL_SELECTIONS) {
throw UnsupportedOperationException()
}
@@ -232,11 +227,7 @@
throw IllegalArgumentException("Cannot insert selection, affordance ID was empty!")
}
- val success =
- interactor.select(
- slotId = slotId,
- affordanceId = affordanceId,
- )
+ val success = interactor.select(slotId = slotId, affordanceId = affordanceId)
return if (success) {
Log.d(TAG, "Successfully selected $affordanceId for slot $slotId")
@@ -318,22 +309,14 @@
)
.apply {
interactor.getSlotPickerRepresentations().forEach { representation ->
- addRow(
- arrayOf(
- representation.id,
- representation.maxSelectedAffordances,
- )
- )
+ addRow(arrayOf(representation.id, representation.maxSelectedAffordances))
}
}
}
private suspend fun queryFlags(): Cursor {
return MatrixCursor(
- arrayOf(
- Contract.FlagsTable.Columns.NAME,
- Contract.FlagsTable.Columns.VALUE,
- )
+ arrayOf(Contract.FlagsTable.Columns.NAME, Contract.FlagsTable.Columns.VALUE)
)
.apply {
interactor.getPickerFlags().forEach { flag ->
@@ -351,10 +334,7 @@
}
}
- private suspend fun deleteSelection(
- uri: Uri,
- selectionArgs: Array<out String>?,
- ): Int {
+ private suspend fun deleteSelection(uri: Uri, selectionArgs: Array<out String>?): Int {
if (selectionArgs == null) {
throw IllegalArgumentException(
"Cannot delete selection, selection arguments not included!"
@@ -372,11 +352,7 @@
)
}
- val deleted =
- interactor.unselect(
- slotId = slotId,
- affordanceId = affordanceId,
- )
+ val deleted = interactor.unselect(slotId = slotId, affordanceId = affordanceId)
return if (deleted) {
Log.d(TAG, "Successfully unselected $affordanceId for slot $slotId")
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 5e1188f..1a0525d 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -1689,6 +1689,12 @@
});
mJavaAdapter.alwaysCollectFlow(communalViewModel.getTransitionFromOccludedEnded(),
getFinishedCallbackConsumer());
+
+ // System ready can be invoked in the middle of user switching, so check for this state
+ // and issue the call manually as that important event was missed.
+ if (mUserTracker.isUserSwitching()) {
+ mUpdateCallback.onUserSwitching(mUserTracker.getUserId());
+ }
}
// Most services aren't available until the system reaches the ready state, so we
// send it here when the device first boots.
diff --git a/packages/SystemUI/src/com/android/systemui/settings/MultiUserUtilsModule.java b/packages/SystemUI/src/com/android/systemui/settings/MultiUserUtilsModule.java
index b9f9b92..05f19ef 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/MultiUserUtilsModule.java
+++ b/packages/SystemUI/src/com/android/systemui/settings/MultiUserUtilsModule.java
@@ -16,6 +16,7 @@
package com.android.systemui.settings;
+import android.app.ActivityManager;
import android.app.IActivityManager;
import android.content.Context;
import android.hardware.display.DisplayManager;
@@ -66,7 +67,7 @@
@Background CoroutineDispatcher backgroundDispatcher,
@Background Handler handler
) {
- int startingUser = userManager.getBootUser().getIdentifier();
+ int startingUser = ActivityManager.getCurrentUser();
UserTrackerImpl tracker = new UserTrackerImpl(context, featureFlagsProvider, userManager,
iActivityManager, dumpManager, appScope, backgroundDispatcher, handler);
tracker.initialize(startingUser);
diff --git a/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt b/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt
index 1a997a7..e1631cc 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt
+++ b/packages/SystemUI/src/com/android/systemui/settings/UserTracker.kt
@@ -16,11 +16,10 @@
package com.android.systemui.settings
-import com.android.systemui.util.annotations.WeaklyReferencedCallback
-
import android.content.Context
import android.content.pm.UserInfo
import android.os.UserHandle
+import com.android.systemui.util.annotations.WeaklyReferencedCallback
import java.util.concurrent.Executor
/**
@@ -31,19 +30,13 @@
*/
interface UserTracker : UserContentResolverProvider, UserContextProvider {
- /**
- * Current user's id.
- */
+ /** Current user's id. */
val userId: Int
- /**
- * [UserHandle] for current user
- */
+ /** [UserHandle] for current user */
val userHandle: UserHandle
- /**
- * [UserInfo] for current user
- */
+ /** [UserInfo] for current user */
val userInfo: UserInfo
/**
@@ -56,39 +49,33 @@
*/
val userProfiles: List<UserInfo>
- /**
- * Add a [Callback] to be notified of chances, on a particular [Executor]
- */
+ /** Is the system in the process of switching users? */
+ val isUserSwitching: Boolean
+
+ /** Add a [Callback] to be notified of chances, on a particular [Executor] */
fun addCallback(callback: Callback, executor: Executor)
- /**
- * Remove a [Callback] previously added.
- */
+ /** Remove a [Callback] previously added. */
fun removeCallback(callback: Callback)
- /**
- * Callback for notifying of changes.
- */
+ /** Callback for notifying of changes. */
@WeaklyReferencedCallback
interface Callback {
- /**
- * Notifies that the current user will be changed.
- */
+ /** Notifies that the current user will be changed. */
fun onBeforeUserSwitching(newUser: Int) {}
/**
- * Same as {@link onUserChanging(Int, Context, Runnable)} but the callback will be
- * called automatically after the completion of this method.
+ * Same as {@link onUserChanging(Int, Context, Runnable)} but the callback will be called
+ * automatically after the completion of this method.
*/
fun onUserChanging(newUser: Int, userContext: Context) {}
/**
- * Notifies that the current user is being changed.
- * Override this method to run things while the screen is frozen for the user switch.
- * Please use {@link #onUserChanged} if the task doesn't need to push the unfreezing of the
- * screen further. Please be aware that code executed in this callback will lengthen the
- * user switch duration. When overriding this method, resultCallback#run() MUST be called
- * once the execution is complete.
+ * Notifies that the current user is being changed. Override this method to run things while
+ * the screen is frozen for the user switch. Please use {@link #onUserChanged} if the task
+ * doesn't need to push the unfreezing of the screen further. Please be aware that code
+ * executed in this callback will lengthen the user switch duration. When overriding this
+ * method, resultCallback#run() MUST be called once the execution is complete.
*/
fun onUserChanging(newUser: Int, userContext: Context, resultCallback: Runnable) {
onUserChanging(newUser, userContext)
@@ -96,15 +83,13 @@
}
/**
- * Notifies that the current user has changed.
- * Override this method to run things after the screen is unfrozen for the user switch.
- * Please see {@link #onUserChanging} if you need to hide jank.
+ * Notifies that the current user has changed. Override this method to run things after the
+ * screen is unfrozen for the user switch. Please see {@link #onUserChanging} if you need to
+ * hide jank.
*/
fun onUserChanged(newUser: Int, userContext: Context) {}
- /**
- * Notifies that the current user's profiles have changed.
- */
+ /** Notifies that the current user's profiles have changed. */
fun onProfilesChanged(profiles: List<@JvmSuppressWildcards UserInfo>) {}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/settings/UserTrackerImpl.kt b/packages/SystemUI/src/com/android/systemui/settings/UserTrackerImpl.kt
index 553d1f5..1863e12 100644
--- a/packages/SystemUI/src/com/android/systemui/settings/UserTrackerImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/settings/UserTrackerImpl.kt
@@ -106,6 +106,9 @@
override var userInfo: UserInfo by SynchronizedDelegate(UserInfo(context.userId, "", 0))
protected set
+ override var isUserSwitching = false
+ protected set
+
/**
* Returns a [List<UserInfo>] of all profiles associated with the current user.
*
@@ -197,6 +200,7 @@
}
override fun onUserSwitching(newUserId: Int, reply: IRemoteCallback?) {
+ isUserSwitching = true
if (isBackgroundUserSwitchEnabled) {
userSwitchingJob?.cancel()
userSwitchingJob =
@@ -210,6 +214,7 @@
}
override fun onUserSwitchComplete(newUserId: Int) {
+ isUserSwitching = false
if (isBackgroundUserSwitchEnabled) {
afterUserSwitchingJob?.cancel()
afterUserSwitchingJob =
@@ -221,7 +226,7 @@
}
}
},
- TAG
+ TAG,
)
}
@@ -349,7 +354,7 @@
private data class DataItem(
val callback: WeakReference<UserTracker.Callback>,
- val executor: Executor
+ val executor: Executor,
) {
fun sameOrEmpty(other: UserTracker.Callback): Boolean {
return callback.get()?.equals(other) ?: true
diff --git a/packages/SystemUI/tests/src/com/android/systemui/settings/UserTrackerImplTest.kt b/packages/SystemUI/tests/src/com/android/systemui/settings/UserTrackerImplTest.kt
index 2e2ac3e..a0ecb80 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/settings/UserTrackerImplTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/settings/UserTrackerImplTest.kt
@@ -231,7 +231,7 @@
"",
"",
UserInfo.FLAG_MANAGED_PROFILE,
- UserManager.USER_TYPE_PROFILE_MANAGED
+ UserManager.USER_TYPE_PROFILE_MANAGED,
)
infoProfile.profileGroupId = id
listOf(info, infoProfile)
@@ -261,7 +261,7 @@
"",
"",
UserInfo.FLAG_MANAGED_PROFILE or UserInfo.FLAG_QUIET_MODE,
- UserManager.USER_TYPE_PROFILE_MANAGED
+ UserManager.USER_TYPE_PROFILE_MANAGED,
)
infoProfile.profileGroupId = id
listOf(info, infoProfile)
@@ -291,7 +291,7 @@
"",
"",
UserInfo.FLAG_MANAGED_PROFILE,
- UserManager.USER_TYPE_PROFILE_MANAGED
+ UserManager.USER_TYPE_PROFILE_MANAGED,
)
infoProfile.profileGroupId = id
listOf(info, infoProfile)
@@ -423,7 +423,7 @@
"",
"",
UserInfo.FLAG_MANAGED_PROFILE,
- UserManager.USER_TYPE_PROFILE_MANAGED
+ UserManager.USER_TYPE_PROFILE_MANAGED,
)
infoProfile.profileGroupId = id
listOf(info, infoProfile)
@@ -469,6 +469,24 @@
assertThat(callback.calledOnProfilesChanged).isEqualTo(0)
}
+ @Test
+ fun testisUserSwitching() =
+ testScope.runTest {
+ tracker.initialize(0)
+ val newID = 5
+ val profileID = newID + 10
+
+ val captor = ArgumentCaptor.forClass(IUserSwitchObserver::class.java)
+ verify(iActivityManager).registerUserSwitchObserver(capture(captor), anyString())
+ assertThat(tracker.isUserSwitching).isFalse()
+
+ captor.value.onUserSwitching(newID, userSwitchingReply)
+ assertThat(tracker.isUserSwitching).isTrue()
+
+ captor.value.onUserSwitchComplete(newID)
+ assertThat(tracker.isUserSwitching).isFalse()
+ }
+
private class TestCallback : UserTracker.Callback {
var calledOnUserChanging = 0
var calledOnUserChanged = 0
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/settings/FakeUserTracker.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/settings/FakeUserTracker.kt
index f3d5b7d..cd76a74 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/settings/FakeUserTracker.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/settings/FakeUserTracker.kt
@@ -33,6 +33,7 @@
private var _userHandle: UserHandle = UserHandle.of(_userId),
private var _userInfo: UserInfo = mock(),
private var _userProfiles: List<UserInfo> = emptyList(),
+ private var _isUserSwitching: Boolean = false,
userContentResolverProvider: () -> ContentResolver = { MockContentResolver() },
userContext: Context = mock(),
private val onCreateCurrentUserContext: (Context) -> Context = { mock() },
@@ -51,6 +52,9 @@
override val userProfiles: List<UserInfo>
get() = _userProfiles
+ override val isUserSwitching: Boolean
+ get() = _isUserSwitching
+
// userContentResolver is lazy because Ravenwood doesn't support MockContentResolver()
// and we still want to allow people use this class for tests that don't use it.
override val userContentResolver: ContentResolver by lazy { userContentResolverProvider() }
@@ -86,11 +90,13 @@
}
fun onUserChanging(userId: Int = _userId) {
+ _isUserSwitching = true
val copy = callbacks.toList()
copy.forEach { it.onUserChanging(userId, userContext) {} }
}
fun onUserChanged(userId: Int = _userId) {
+ _isUserSwitching = false
val copy = callbacks.toList()
copy.forEach { it.onUserChanged(userId, userContext) }
}