diff --git a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java index 1e50c80f0e719..6aea92fbe730c 100644 --- a/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java +++ b/services/companion/java/com/android/server/companion/CompanionDeviceManagerService.java @@ -82,6 +82,7 @@ import android.net.NetworkPolicyManager; import android.os.Binder; import android.os.Environment; import android.os.Handler; +import android.os.Message; import android.os.Parcel; import android.os.PowerWhitelistManager; import android.os.RemoteCallbackList; @@ -185,6 +186,7 @@ public class CompanionDeviceManagerService extends SystemService private final CompanionDeviceManagerServiceInternal mLocalService = new LocalService(this); final Handler mMainHandler = Handler.getMain(); + private final PersistUserStateHandler mUserPersistenceHandler = new PersistUserStateHandler(); private CompanionDevicePresenceController mCompanionDevicePresenceController; /** @@ -366,9 +368,8 @@ public class CompanionDeviceManagerService extends SystemService final List updatedAssociations = mAssociationStore.getAssociationsForUser(userId); - final Map> usedIdsForUser = getPreviouslyUsedIdsForUser(userId); - BackgroundThread.getHandler().post(() -> - mPersistentStore.persistStateForUser(userId, updatedAssociations, usedIdsForUser)); + + mUserPersistenceHandler.postPersistUserState(userId); // Notify listeners if ADDED, REMOVED or UPDATED_ADDRESS_CHANGED. // Do NOT notify when UPDATED_ADDRESS_UNCHANGED, which means a minor tweak in association's @@ -381,6 +382,13 @@ public class CompanionDeviceManagerService extends SystemService restartBleScan(); } + private void persistStateForUser(@UserIdInt int userId) { + final List updatedAssociations = + mAssociationStore.getAssociationsForUser(userId); + final Map> usedIdsForUser = getPreviouslyUsedIdsForUser(userId); + mPersistentStore.persistStateForUser(userId, updatedAssociations, usedIdsForUser); + } + private void notifyListeners( @UserIdInt int userId, @NonNull List associations) { mListeners.broadcast((listener, callbackUserId) -> { @@ -1349,4 +1357,29 @@ public class CompanionDeviceManagerService extends SystemService mService.associationCleanUp(profile); } } + + /** + * This class is dedicated to handling requests to persist user state. + */ + @SuppressLint("HandlerLeak") + private class PersistUserStateHandler extends Handler { + PersistUserStateHandler() { + super(BackgroundThread.get().getLooper()); + } + + /** + * Persists user state unless there is already an outstanding request for the given user. + */ + synchronized void postPersistUserState(@UserIdInt int userId) { + if (!hasMessages(userId)) { + sendMessage(obtainMessage(userId)); + } + } + + @Override + public void handleMessage(@NonNull Message msg) { + final int userId = msg.what; + persistStateForUser(userId); + } + } }