• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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.settings
18 
19 import android.content.ContentResolver
20 import android.content.Context
21 import android.os.UserHandle
22 import androidx.annotation.VisibleForTesting
23 import com.android.systemui.broadcast.BroadcastDispatcher
24 import com.android.systemui.util.Assert
25 import java.lang.IllegalStateException
26 
27 /**
28  * Tracks a reference to the context for the current user
29  *
30  * Constructor is injected at SettingsModule
31  */
32 class CurrentUserContextTracker internal constructor(
33     private val sysuiContext: Context,
34     broadcastDispatcher: BroadcastDispatcher
35 ) : CurrentUserContentResolverProvider {
36     private val userTracker: CurrentUserTracker
37     private var initialized = false
38 
39     private var _curUserContext: Context? = null
40     val currentUserContext: Context
41         get() {
42             if (!initialized) {
43                 throw IllegalStateException("Must initialize before getting context")
44             }
45             return _curUserContext!!
46         }
47 
48     override val currentUserContentResolver: ContentResolver
49         get() = currentUserContext.contentResolver
50 
51     init {
52         userTracker = object : CurrentUserTracker(broadcastDispatcher) {
onUserSwitchednull53             override fun onUserSwitched(newUserId: Int) {
54                 handleUserSwitched(newUserId)
55             }
56         }
57     }
58 
initializenull59     fun initialize() {
60         initialized = true
61         userTracker.startTracking()
62         _curUserContext = makeUserContext(userTracker.currentUserId)
63     }
64 
65     @VisibleForTesting
handleUserSwitchednull66     fun handleUserSwitched(newUserId: Int) {
67         _curUserContext = makeUserContext(newUserId)
68     }
69 
makeUserContextnull70     private fun makeUserContext(uid: Int): Context {
71         Assert.isMainThread()
72         return sysuiContext.createContextAsUser(UserHandle.of(uid), 0)
73     }
74 }