Android Multiprofile android-multiprofile
Gives guidance on multiprofile pitfalls, gotchas, and established solutions.
Use it when you are refactoring Chrome for Android to support multiple profiles, removing `getLastUsedRegularProfile()`, scoping `SharedPreferences` or `ProfileKeyedMap` / `ProfileTokenUtils`, or changing how a feature interacts with profiles.
- Our test
- —
- not tested yet
- GitHub stars
- 26k
- chromium/chromium
- Added by
- 0
- members
- Updated
- Dec 6
- commit 8cf236c
- Content
- 1 file
- no scripts · 13 KB
- License
- BSD 3-Clause
- free to use
What our test found
Not tested yet. Our model tries every skill on a realistic request and scores the result, the most popular skills first. Until then, the safety checks on the right still apply.
name: android-multiprofile description: >- Gives guidance on multiprofile pitfalls, gotchas, and established solutions. Use whenever you are refactoring Chrome for Android to support multiple profiles, removing `getLastUsedRegularProfile()`, scoping `SharedPreferences` or `ProfileKeyedMap` / `ProfileTokenUtils`, or changing how a feature interacts with profiles.
Chrome for Android Multiprofile Guide
Clank has been long assuming that only 1 global profile exists in the browser. We now aim to support multiple profiles, and expect to see significant refactoring of existing code to support this.
Desktop shared code already supports multiple profiles; prefer removing #if !BUILDFLAG(IS_ANDROID) guards over inventing Android-only paths. Clank's issues live in Android-specific Java/C++ glue built around pre-native UI startup, one regular profile (Default), one primary Incognito profile, and APK-wide OS APIs.
Use Established Solutions
- Tab / page code:
tab.getProfile()orProfile.fromWebContents(webContents). - Window / Activity UI: Observe a
Profilesupplier (TabModelSelectorProfileSupplierfor active regular/OTR switches, or aMonotonicObservableSupplier<Profile>/NullableObservableSupplier<Profile>); store a directProfilefield only when post-native and destroyed before the profile.ActivityProfileProvider(OneshotSupplier<ProfileProvider>) resolves the activity's profile from its intent token (failing closed if invalid; falling back togetLastUsedRegularProfile()only when no token is present), without tracking regular/OTR switches — mark any still-missing upstream routing withTODO(crbug.com/40254448). - Java-owned per-profile state (`ProfileKeyedMap`): Use
static final ProfileKeyedMap<T>(createMapOfDestroyables()). SetProfileSelection.REDIRECTED_TO_ORIGINAL(shared with OTR) vs. defaultOWN_INSTANCEon the map instead of manually callinggetOriginalProfile(). UseProfileKeyedMap<Boolean>to replacestatic boolean sInitialized. - C++ `KeyedService` & JNI bridges: Pass
@JniType("Profile*") Profileacross JNI (FooFactory.getForProfile(profile)) and delete C++ ambient calls (GetLastUsedProfile*,GetActiveUserProfile,GetPrimaryUserProfile,GetLastUsedRegularProfileKey). Do not wrap stateless shims inProfileKeyedMap; for stateful wrappers around a C++KeyedService, prefer C++ owning aScopedJavaGlobalRefand destroying it inShutdown(). - Internal Intents: Use
ProfileTokenUtils(addProfileToIntent,resolveProfileToken,retrieveProfileFromIntent,getNotificationTag) to encode which profile to use. - Preferences: Prefer
UserPrefs.get(profile)(PrefService) for per-profile prefs (sync, policy, OTR, and deletion work automatically) unless accessed off the UI thread or before native; otherwise useProfileSharedPreferences.get(profile)/getSideStore(profile, baseFileName). KeepChromeSharedPreferences.getInstance()andChromeSharedPreferences.getSideStore(fileName)strictly for device/app-wide state. Never bypass viaContextUtils.getAppSharedPreferences(), directcontext.getSharedPreferences(name, ...), or//base'sSharedPreferencesManagerdirectly. - Disk / cache paths: Key by
profile.getBaseName()("Default","Profile 1"). Notechrome::GetUserCacheDirectory()maps"Default"to bareContext.getCacheDir()and secondary profiles togetCacheDir()/<baseName>. - Before native is initialized:
- Defer via supplier (preferred): Hold the
Activity'sOneshotSupplier<ProfileProvider>and run work once populated post-native. - Java state:
PreNativeProfileKeyedMap<T>(pass factory andDestroyable::destroycleanup to the constructor; acts as a singlefactory.apply(null)instance whenAndroidMultiprofileis disabled. When enabled,getForProfile(null)keys one instance togetLastUsedProfileBaseName()and throwsIllegalStateExceptiononceProfileManager.isInitialized()— re-fetch with a non-nullProfilepost-native since it is destroyed if the base name wasnullor mismatched). - Preferences:
ProfileSharedPreferences.forProfileDir(profileDirName)(orgetSideStoreForProfileDir(profileDirName, baseFileName)for side stores; pass"Default"ifgetLastUsedProfileBaseName()isnull). - Tokens & notifications:
ProfileTokenUtils.parseProfileToken()andgetNotificationTagFromIntent()work pre-native (e.g. to inspect tokens or dismiss a notification from a coldBroadcastReceiver). - Enumerating profiles: C++
ProfileAttributesStoragecovers unloaded profiles (ProfileManager.getLoadedProfiles()returns only loaded regular profiles; JavaProfileAttributesStorage.get()currently exposes public primary-account lookups and observers, skipping signed-out/omitted profiles).
Non-Obvious Pitfalls
- Startup, recreation, and Activity reuse:
AsyncInitializationActivitygatesonStartWithNative,onResumeWithNative, andfinishNativeInitializationonProfileProvider.- In
SynchronousInitializationActivity, async profile load runs aftersuper.onCreate()(including restoredFragments/DialogFragments),onStart(), andonResume(). - Note when
Intents are rewritten/replaced, preserve their token withProfileTokenUtils.copyProfileToken(from, to). Recents/process-death/config-change recreation can strip or rewrite launch intent extras (IntentHandler.rewriteFromHistoryIntent,sClearIntentWhenRecreated, Settings-in-tab recreation); do not assume launch extras survive. singleTop/singleTask/singleInstance/singleInstancePerTaskactivities receiveonNewIntent()— route to the profile's window, recreate, or reject (don't rebind a live window to a different profile).- Profile teardown & UAF:
ProfileManager.Observer.onProfileAddedfires only for regular profiles, whileonProfileDestroyedfires for both regular and OTR profiles.- Teardown runs:
onProfileWillBeDestroyed(shutdownStarted() == true,onProfileDestroyed+ProfileKeyedMapcleanup while nativeProfile*is live) → OTR teardown →KeyedServiceshutdown →onNativeDestroyed. - Never call
sProfileMap.destroy()from a per-windowdestroy(). Supply a cleanup action to unregister global observers and clearObserverLists, and null-check optional services beforegetForProfile(factories must return non-null). - Java-owned C++ bridges holding
raw_ptr<KeyedService>orScopedObservationmust tear down viaProfileKeyedMaporProfileObserver::OnProfileWillBeDestroyed, not GC orActivity.onDestroy(seesend_tab_to_self_android_bridge.cc). - Do not oneshot-read observable
Profilesuppliers; re-check active profile,shutdownStarted(), andisFinishing()in async callbacks. - Implicit contamination in "already per-profile" features:
- Features reading
UserPrefsorTrackerFactory.getTrackerForProfile()still leak when they cache values instaticfields/maps, gate on a global pref (e.g. first-launch timestamps) or counter (skewing UMA/Finch), or write cachedSharedPreferencesback into syncedUserPrefs. - Scoping files does not scope
staticin-memory caches over them, nor startup GC tasks that purge unopened windows belonging to unloaded profiles. - AndroidX
Preferencewidgets auto-persist theirandroid:keyinto default globalSharedPreferencesunless persistence is disabled or backed by aPreferenceDataStore. - `ProfileTokenUtils` subtleties:
addProfileToIntentis post-native only, requires an explicit self component/package already set on theIntent(foraddTrustedIntentExtras), and setsintent.setIdentifier(token)soPendingIntents don't overwrite across profiles. It assertsgetIdentifier() == null— don't pre-set one or call twice; userequestCodefor within-profile uniqueness.retrieveProfileFromIntentruns its callback with `null` if a failure occurs - never fall back togetLastUsedRegularProfile().- Encoded tokens persist in OS
PendingIntents and notification tags; keepProfileTokenwire-compatible. When migrating togetNotificationTag, cancel legacy untagged notifications only for!profile.isOffTheRecord() && profile.isInitialProfile(). - Multiple Incognito profiles exist: Each regular
Profilehas its own primary OTR profile (and custom OTRs can also exist). UseIncognitoTabHostUtils.doIncognitoTabsExistForProfile(otrProfile)/isIncognitoTabModelActive(otrProfile)for profile-scoped queries. OtrProfileIdis only unique within its owning regularProfile(every regular profile sharesOtrProfileId.getPrimaryOtrProfileId()); compareProfileinstances, notOtrProfileIdorisOffTheRecord().- Do not conflate
isOffTheRecord()withisIncognitoBranded()(Ephemeral CCT and enterprise isolated profiles are OTR without Incognito UI).
Easily Missed Android Surfaces
- Activity / window / tab lookups:
ApplicationStatus.getLastTrackedFocusedActivity()/getRunningActivities(),MultiWindowUtils.getLastAccessedWindowId(), andTabWindowManageriterators span all profiles (plus CCT/Incognito/PiP); useTabWindowManagerSingleton.getForProfile(profile)(ProfileTabWindowLookup) for profile-scoped tab/window queries. - `BackgroundTaskScheduler` / `JobScheduler`: Static
TaskIdsmap 1:1 to APK-global job IDs — scheduling or canceling for Profile B overwrites/cancels Profile A even withPersistableBundleextras. Prefer a single dispatcher job that fans out across profiles or schedules the earliest deadline from per-profile state. - `Service`s, `BroadcastReceiver`s, `ContentProvider`s: One instance per APK UID, often cold/pre-native (foreground services,
DownloadManagerService, 3P autofillContentProvider). - OS, AndroidX & GMSCore APK-wide state: Notification channels,
PackageManagercomponent toggles (watch cleanup wiping shared state),AppCompatDelegateglobal night mode, OS donors (AppSearch, Assist, Digital Wellbeing, Backup), OS Settings endpoints, and app-scoped AndroidX/GMSCore APIs (Cast,GCMDriver/InstanceIDsubtypes, CredMan/UPM/WebAuthn). - Identity, enterprise & consents:
AccountManagerFacadeexposes all OS-user accounts and Android useskMirrorcookie reconciliation. Do not auto-delete profile dirs on OS account removal or equate a managed Chrome profile with an Android Work Profile. Confirm install-wide vs. per-profile scope for consents and ambiguous UX with product/owners.
Flags & Testing
We plan to define critical multiprofile behavior in Public Transit tests that are landed disabled, with the goal to re-enable these tests when we fix the underlying issue. Never forget to remove the @DisabledTest(message = "https://crbug.com/40254448") when you expect to fix the underlying issue. If adding new critical behavior, codify it in a new test, but not all bug fixes or tiny changes need this level of coverage.
- Feature flag (off by default, including in tests):
ChromeFeatureList.sAndroidMultiprofile/ChromeFeatureList.ANDROID_MULTIPROFILE/chrome::android::kAndroidMultiprofile(preferprofiles::IsMultipleProfilesEnabled()in C++) gates multi-profile creation, startup, and account filtering. - Avoid single `@Mock Profile` false confidence:
ProfileManager.setLastUsedProfileForTesting(),Profile.setProfileFromWebContentsForTesting(), and single-slotUserPrefs.setPrefServiceForTesting()/FooFactory.setInstanceForTesting()hide wrong-profile bugs, while mockgetOriginalProfile()andgetBaseName()returnnull. - Test types
- Manual testing: Launch with
--enable-features=AndroidMultiprofile --profile-directory=<name>to start in (or create) a profile, and checkchrome://version(Profile Path) to verify which profile a window is using. - Preferred: Java instrumentation tests (Public Transit): Follow
MultiProfileWindowTestunderchrome/android/javatests/.../profiles/(@DoNotBatch,@MinAndroidSdkLevel(VERSION_CODES.S),@Restriction(DeviceRestriction.RESTRICTION_TYPE_NON_AUTO),ANDROID_MULTIPROFILE,station.getOriginalProfile(),openNewWindowInNewProfileFast(name), andBasePageStation.Builder#inNewWindow(profile)). Beware legacy helpers (SigninTestRule,SigninTestUtil,SyncTestUtil,BookmarkTestUtil) that callgetLastUsedRegularProfile(). - Robolectric (Java unit tests): Use two real profiles —
TestProfile.createRegular("Default")andTestProfile.createRegular("Profile 1")(plusTestProfile.createIncognito(testProfile)),TestProfileProvider, andFakeProfileAttributesStorage. - C++ `unit_tests`: Call
TestingProfileManager::SetUp()andCreateTestingProfile(...)to test with multipleTestingProfileinstances. - C++ `android_browsertests`: Enable
chrome::android::kAndroidMultiprofileand useprofiles::testing::CreateProfileSync()(orGenerateNextProfileDirectoryPath()/CreateMultiProfileAsync()).