1 /*
2  * Copyright (C) 2014 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.launcher3.compat;
18 
19 import android.annotation.TargetApi;
20 import android.content.Context;
21 import android.os.Build;
22 import android.os.UserManager;
23 
24 import com.android.launcher3.util.LongArrayMap;
25 
26 import java.util.HashMap;
27 
28 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
29 public class UserManagerCompatV17 extends UserManagerCompatV16 {
30 
31     protected LongArrayMap<UserHandleCompat> mUsers;
32     // Create a separate reverse map as LongArrayMap.indexOfValue checks if objects are same
33     // and not {@link Object#equals}
34     protected HashMap<UserHandleCompat, Long> mUserToSerialMap;
35 
36     protected UserManager mUserManager;
37 
UserManagerCompatV17(Context context)38     UserManagerCompatV17(Context context) {
39         mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
40     }
41 
getSerialNumberForUser(UserHandleCompat user)42     public long getSerialNumberForUser(UserHandleCompat user) {
43         synchronized (this) {
44             if (mUserToSerialMap != null) {
45                 Long serial = mUserToSerialMap.get(user);
46                 return serial == null ? 0 : serial;
47             }
48         }
49         return mUserManager.getSerialNumberForUser(user.getUser());
50     }
51 
getUserForSerialNumber(long serialNumber)52     public UserHandleCompat getUserForSerialNumber(long serialNumber) {
53         synchronized (this) {
54             if (mUsers != null) {
55                 return mUsers.get(serialNumber);
56             }
57         }
58         return UserHandleCompat.fromUser(mUserManager.getUserForSerialNumber(serialNumber));
59     }
60 
61     @Override
enableAndResetCache()62     public void enableAndResetCache() {
63         synchronized (this) {
64             mUsers = new LongArrayMap<>();
65             mUserToSerialMap = new HashMap<>();
66             UserHandleCompat myUser = UserHandleCompat.myUserHandle();
67             long serial = mUserManager.getSerialNumberForUser(myUser.getUser());
68             mUsers.put(serial, myUser);
69             mUserToSerialMap.put(myUser, serial);
70         }
71     }
72 }
73 
74