1/*
2 * Copyright (C) 2012 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
17package com.android.settings.users;
18
19import android.content.BroadcastReceiver;
20import android.content.Context;
21import android.content.Intent;
22import android.content.SharedPreferences;
23import android.os.UserHandle;
24import android.os.UserManager;
25import com.android.settings.Utils;
26
27
28/**
29 * Watches for changes to Me Profile in Contacts and writes the photo to the User Manager.
30 */
31public class ProfileUpdateReceiver extends BroadcastReceiver {
32
33    private static final String KEY_PROFILE_NAME_COPIED_ONCE = "name_copied_once";
34
35    @Override
36    public void onReceive(final Context context, Intent intent) {
37        // Profile changed, lets get the photo and write to user manager
38        new Thread() {
39            public void run() {
40                Utils.copyMeProfilePhoto(context, null);
41                copyProfileName(context);
42            }
43        }.start();
44    }
45
46    static void copyProfileName(Context context) {
47        SharedPreferences prefs = context.getSharedPreferences("profile", Context.MODE_PRIVATE);
48        if (prefs.contains(KEY_PROFILE_NAME_COPIED_ONCE)) {
49            return;
50        }
51
52        int userId = UserHandle.myUserId();
53        UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
54        String profileName = Utils.getMeProfileName(context, false /* partial name */);
55        if (profileName != null && profileName.length() > 0) {
56            um.setUserName(userId, profileName);
57            // Flag that we've written the profile one time at least. No need to do it in the future.
58            prefs.edit().putBoolean(KEY_PROFILE_NAME_COPIED_ONCE, true).commit();
59        }
60    }
61}
62