1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.systemui.user.utils
18
19 import android.content.Context
20 import android.os.UserHandle
21 import androidx.core.content.getSystemService
22 import com.android.systemui.dagger.qualifiers.Application
23
24 /**
25 * Provides instances of a [system service][Context.getSystemService] created with
26 * [the context of a specified user][Context.createContextAsUser].
27 *
28 * Some services which have only `@UserHandleAware` APIs operate on the user id available from
29 * [Context.getUser], the context used to retrieve the service. This utility helps adapt a per-user
30 * API model to work in multi-user manner.
31 *
32 * Example usage:
33 * ```
34 * @Provides
35 * fun scopedUserManager(@Application ctx: Context): UserScopedService<UserManager> {
36 * return UserScopedServiceImpl(ctx, UserManager::class)
37 * }
38 *
39 * class MyUserHelper @Inject constructor(
40 * private val userMgr: UserScopedService<UserManager>,
41 * ) {
42 * fun isPrivateProfile(user: UserHandle): UserManager {
43 * return userMgr.forUser(user).isPrivateProfile()
44 * }
45 * }
46 * ```
47 */
interfacenull48 fun interface UserScopedService<T> {
49 /** Create a service instance for the given user. */
50 fun forUser(user: UserHandle): T
51 }
52
53 class UserScopedServiceImpl<T : Any>(
54 @Application private val context: Context,
55 private val serviceType: Class<T>,
56 ) : UserScopedService<T> {
forUsernull57 override fun forUser(user: UserHandle): T {
58 val context =
59 if (context.user == user) {
60 context
61 } else {
62 context.createContextAsUser(user, 0)
63 }
64 return requireNotNull(context.getSystemService(serviceType))
65 }
66 }
67