Home | History | Annotate | Download | only in utils
      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 
     17 package com.android.inputmethod.latin.utils;
     18 
     19 import android.content.res.Configuration;
     20 import android.content.res.Resources;
     21 
     22 import java.util.Locale;
     23 
     24 public 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.
     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             final Locale oldLocale = conf.locale;
     40             final boolean needsChange = (newLocale != null && !newLocale.equals(oldLocale));
     41             try {
     42                 if (needsChange) {
     43                     conf.locale = newLocale;
     44                     res.updateConfiguration(conf, null);
     45                 }
     46                 return job(res);
     47             } finally {
     48                 if (needsChange) {
     49                     conf.locale = oldLocale;
     50                     res.updateConfiguration(conf, null);
     51                 }
     52             }
     53         }
     54     }
     55 }
     56