LocaleSpanCompatUtils.java revision a92fead202aebdc5e98ce0b24aa9029b46a1e8d2
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 17package com.android.inputmethod.compat; 18 19import com.android.inputmethod.annotations.UsedForTesting; 20import com.android.inputmethod.compat.CompatUtils; 21 22import java.lang.reflect.Constructor; 23import java.lang.reflect.Method; 24import java.util.Locale; 25 26@UsedForTesting 27public final class LocaleSpanCompatUtils { 28 // Note that LocaleSpan(Locale locale) has been introduced in API level 17 29 // (Build.VERSION_CODE.JELLY_BEAN_MR1). 30 private static Class<?> getLocalSpanClass() { 31 try { 32 return Class.forName("android.text.style.LocaleSpan"); 33 } catch (ClassNotFoundException e) { 34 return null; 35 } 36 } 37 private static final Constructor<?> LOCALE_SPAN_CONSTRUCTOR; 38 private static final Method LOCALE_SPAN_GET_LOCALE; 39 static { 40 final Class<?> localeSpanClass = getLocalSpanClass(); 41 LOCALE_SPAN_CONSTRUCTOR = CompatUtils.getConstructor(localeSpanClass, Locale.class); 42 LOCALE_SPAN_GET_LOCALE = CompatUtils.getMethod(localeSpanClass, "getLocale"); 43 } 44 45 @UsedForTesting 46 public static boolean isLocaleSpanAvailable() { 47 return (LOCALE_SPAN_CONSTRUCTOR != null && LOCALE_SPAN_GET_LOCALE != null); 48 } 49 50 @UsedForTesting 51 public static Object newLocaleSpan(final Locale locale) { 52 return CompatUtils.newInstance(LOCALE_SPAN_CONSTRUCTOR, locale); 53 } 54 55 @UsedForTesting 56 public static Locale getLocaleFromLocaleSpan(final Object localeSpan) { 57 return (Locale) CompatUtils.invoke(localeSpan, null, LOCALE_SPAN_GET_LOCALE); 58 } 59} 60