1/*
2 * Copyright (C) 2013 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.inputmethod.latin.utils;
18
19import android.content.res.Configuration;
20import android.content.res.Resources;
21
22import java.util.Locale;
23
24public abstract class RunInLocale<T> {
25    private static final Object sLockForRunInLocale = new Object();
26
27    protected abstract T job(final Resources res);
28
29    /**
30     * Execute {@link #job(Resources)} method in specified system locale exclusively.
31     *
32     * @param res the resources to use.
33     * @param newLocale the locale to change to. Run in system locale if null.
34     * @return the value returned from {@link #job(Resources)}.
35     */
36    public T runInLocale(final Resources res, final Locale newLocale) {
37        synchronized (sLockForRunInLocale) {
38            final Configuration conf = res.getConfiguration();
39            if (newLocale == null || newLocale.equals(conf.locale)) {
40                return job(res);
41            }
42            final Locale savedLocale = conf.locale;
43            try {
44                conf.locale = newLocale;
45                res.updateConfiguration(conf, null);
46                return job(res);
47            } finally {
48                conf.locale = savedLocale;
49                res.updateConfiguration(conf, null);
50            }
51        }
52    }
53}
54