android更改應用語言

/**
 * 更改應用語言
 */
public class LangugeUtils {
    /**
     * 更改應用語言
     *
     * @param  context
     * @param languageNameShort
     */
    public static void changeAppLanguage(Context context, String languageNameShort) {
        DisplayMetrics metrics =context. getResources().getDisplayMetrics();
        Configuration configuration =context.getResources().getConfiguration();

        switch (languageNameShort){
            case "zh_CN":
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    configuration.setLocale(Locale.SIMPLIFIED_CHINESE);
                } else {
                    configuration.locale = Locale.SIMPLIFIED_CHINESE;
                }
                break;
            case "zh_TW":
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    configuration.setLocale(Locale.TRADITIONAL_CHINESE);
                } else {
                    configuration.locale = Locale.TRADITIONAL_CHINESE;
                }
                break;
            case "en":
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    configuration.setLocale(Locale.ENGLISH);
                } else {
                    configuration.locale = Locale.ENGLISH;
                }
                break;
        }

        context.getResources().updateConfiguration(configuration, metrics);
        //重新啓動Activity
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
    }
}

//第二種

//application中
@Override
    public void onCreate() {
        super.onCreate();
        appContext = getApplicationContext();
        intance = this;
        context = this;
        registerActivityLifecycleCallbacks(callbacks);
    }

    ActivityLifecycleCallbacks callbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            String language = (String) SPUtils.get(getApplicationContext(), SPUtils.language, "");
            String country = (String) SPUtils.get(getApplicationContext(), SPUtils.country, "");
            if (!TextUtils.isEmpty(language) && !TextUtils.isEmpty(country)) {
                //強制修改應用語言
                if (!MultiLanguageUtils.isSameWithSetting(activity)) {
                    Locale locale = new Locale(language, country);
                    MultiLanguageUtils.changeAppLanguage(activity, locale, false);
//                    activity.recreate();
                }
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }
        //Activity 其它生命週期的回調
    };

    @Override
    protected void attachBaseContext(Context base) {
        //系統語言等設置發生改變時會調用此方法,需要要重置app語言
        super.attachBaseContext(MultiLanguageUtils.attachBaseContext(base));
    }
//工具類
public class MultiLanguageUtils {

    public static Context attachBaseContext(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return createConfigurationResources(context);
        } else {
            setConfiguration(context);
            return context;
        }
    }

    /**
     * 設置語言
     *
     * @param context
     */
    public static void setConfiguration(Context context) {
        Locale appLocale = getAppLocale(context);

        //如果本地有語言信息,以本地爲主,如果本地沒有使用默認Locale
        Locale locale = null;
        String language = (String) SPUtils.get(context, SPUtils.language, "");
        String country = (String) SPUtils.get(context, SPUtils.country, "");
        if (!TextUtils.isEmpty(language) && !TextUtils.isEmpty(country)) {
            if (isSameLocal(appLocale, language, country)) {
                locale = appLocale;
            } else {
                locale = new Locale(language, country);
            }
        } else {
            locale = appLocale;
        }

        Configuration configuration = context.getResources().getConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        resources.updateConfiguration(configuration, dm);//語言更換生效的代碼!
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context createConfigurationResources(Context context) {
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        Locale appLocale = getAppLocale(context);

        //如果本地有語言信息,以本地爲主,如果本地沒有使用默認Locale
        Locale locale = null;
        String language = (String) SPUtils.get(context, SPUtils.language, "");
        String country = (String) SPUtils.get(context, SPUtils.country, "");
        if (!TextUtils.isEmpty(language) && !TextUtils.isEmpty(country)) {
            if (isSameLocal(appLocale, language, country)) {
                locale = appLocale;
            } else {
                locale = new Locale(language, country);
            }
        } else {
            locale = appLocale;
        }
        configuration.setLocale(locale);
        configuration.setLocales(new LocaleList(locale));
        return context.createConfigurationContext(configuration);
    }

    /**
     * 更改應用語言
     *
     * @param
     * @param locale      語言地區
     * @param persistence 是否持久化
     */
    public static void changeAppLanguage(Context context, Locale locale, boolean persistence) {
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            configuration.setLocale(locale);
            configuration.setLocales(new LocaleList(locale));
            context.createConfigurationContext(configuration);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale);
        } else {
            configuration.locale = locale;
        }
        resources.updateConfiguration(configuration, metrics);

        if (persistence) {
            saveLanguageSetting(context, locale);
        }
    }

    //保存多語言信息到sp中
    public static void saveLanguageSetting(Context context, Locale locale) {
        SPUtils.set(context, SPUtils.language, locale.getLanguage());
        SPUtils.set(context, SPUtils.country, locale.getCountry());
    }

    //獲取本地應用的實際的多語言信息
    public static Locale getAppLocale(Context context) {
        //獲取應用語言
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        Locale locale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = configuration.getLocales().get(0);
        } else {
            locale = configuration.locale;
        }
        return locale;
    }

    //判斷sp中和app中的多語言信息是否相同
    public static boolean isSameWithSetting(Context context) {
        Locale locale = getAppLocale(context);
        String language = locale.getLanguage();
        String country = locale.getCountry();

        String sp_language = (String) SPUtils.get(context, SPUtils.language, "");
        String sp_country = (String) SPUtils.get(context, SPUtils.country, "");
        if (language.equals(sp_language) && country.equals(sp_country)) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isSameLocal(Locale appLocale, String sp_language, String sp_country) {
        String appLanguage = appLocale.getLanguage();
        String appCountry = appLocale.getCountry();
        if (appLanguage.equals(sp_language) && appCountry.equals(sp_country)) {
            return true;
        } else {
            return false;
        }
    }

    //修改應用內語言設置
    public static void changeLanguage(Context context, String language, String area) {
        if (TextUtils.isEmpty(language) && TextUtils.isEmpty(area)) {
            LogUtils.log("changeLanguage", language+area);
            //如果語言和地區都是空,那麼跟隨系統
            SPUtils.set(context, SPUtils.language, language);
            SPUtils.set(context, SPUtils.country, area);
        } else {
            //不爲空,那麼修改app語言,並true是把語言信息保存到sp中,false是不保存到sp中
            Locale newLocale = new Locale(language, area);
            changeAppLanguage(context, newLocale, true);
        }
        //重啓app,這一步一定要加上,如果不重啓app,可能打開新的頁面顯示的語言會不正確
        Intent intent = new Intent(BaseApplication.appContext, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        BaseApplication.appContext.startActivity(intent);
//        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章