Android多语言切换(适用于8.0以上)

首先关于语言配置的文件就不赘述了,在setting里面新建resoure资源就可以了。下面主要讲的是如何针对于8.0版本以上的系统做适配,因为8.0对多语言的改动还是蛮大的。

一.8.0之前如何写多语言

  Resources resources = context.getApplicationContext().getResources();
  DisplayMetrics dm = resources.getDisplayMetrics();
  Configuration config = resources.getConfiguration();
  Locale locale = getSetLanguageLocale(context);//获取sp里面保存的语言
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    config.setLocale(locale);
  } else {
    config.locale = locale;
  }
  resources.updateConfiguration(config, dm);

/**
     * 获取选择的语言设置
     *
     * @param context
     * @return
     */
    private static Locale getSetLanguageLocale(Context context) {
        switch (Store.getLanguageType()) {
            case "null"://跟随系统
                return getSystemLocale();
            case "zh"://英语
                return Locale.CHINESE;
            case "en"://汉语
                return Locale.ENGLISH;
            default://默认 汉语
                return Locale.CHINESE;
        }
    }
/**
 * 本地存储语言
 *
 * SharedPrefences操作方法
 */

public class Store {
    public static String LANGUAGE_KEY = "language";
    public static String LANGUAGE_TYPE_CHINESE = "zh";
    public static String LANGUAGE_TYPE_ENGLISH = "en";
    public static String LANGUAGE_TYPE_NUll = "null";

    public static String getLanguageType() {
        Context context = ContextUtil.getcontext();
        SharedPreferences sp = context.getSharedPreferences(LANGUAGE_KEY, Context.MODE_WORLD_READABLE);
        return sp.getString(LANGUAGE_KEY, LANGUAGE_TYPE_NUll);
    }


    public static void insertLanguageType(String type) {
        Context context = ContextUtil.getcontext();
        SharedPreferences sp = context.getSharedPreferences(LANGUAGE_KEY, Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(LANGUAGE_KEY, type);
        editor.commit();
    }
}

二.8.0后作出的改动

public static void changeLanguage() {
        Context context = ContextUtil.getcontext();
        //获取设置
        String sta = Store.getLanguageType();
        if (!Store.LANGUAGE_TYPE_NUll.equals(sta)) {
            Resources resources = context.getApplicationContext().getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            Configuration config = resources.getConfiguration();
            Locale locale = getSetLanguageLocale(context);//获取sp里面保存的语言
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                config.setLocale(locale);
            } else {
                config.locale = locale;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                LocaleList localeList = new LocaleList(locale);
                LocaleList.setDefault(localeList);
                config.setLocales(localeList);
                context.getApplicationContext().createConfigurationContext(config);
                Locale.setDefault(locale);
            }
            resources.updateConfiguration(config, dm);
        }
    }

当版本8.0以后,增加了通过config.setLocales去修改多语言。

当然app都会在Application类的onCreate方法执行读取该APP设置的语言进行设置更换的方法,但是我们现在还需要在Application类加这段代码。

@Override
public void onConfigurationChanged(Configuration newConfig) {
   super.onConfigurationChanged(newConfig);
   ChangeLanguageUtil.changeLanguage();
}

三.在高版本中废弃了updateConfiguration方法,替代方法为createConfigurationContext。

意思就是多语言需要传递到context,所以每个context都得有,所以想了一个办法,每个activity都会有基类即是自己定义的BaseActivity,所以我们只要在基类加如下代码即可适配8.0或更高版本。

@Override
protected void attachBaseContext(Context base) {
  super.attachBaseContext(LanguageUtils.attachBaseContext(base));
}
public class LanguageUtils {
    public static Context attachBaseContext(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 8.0需要使用createConfigurationContext处理
            return updateResources(context);
        } else {
            return context;
        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context) {
        Resources resources = context.getResources();
        Locale locale = getSetLanguageLocale(context);//获取sp里面保存的语言
        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        configuration.setLocales(new LocaleList(locale));
        return context.createConfigurationContext(configuration);
    }

    /**
     * 获取选择的语言设置
     *
     * @param context
     * @return
     */
    private static Locale getSetLanguageLocale(Context context) {
        switch (Store.getLanguageType()) {
            case "null"://跟随系统
                return getSystemLocale();
            case "zh"://汉语
                return Locale.CHINESE;
            case "en"://英语
                return Locale.ENGLISH;
            default://默认 汉语
                return Locale.CHINESE;
        }
    }

    /**
     * 获取系统local
     *
     * @return
     */
    public static Locale getSystemLocale() {
        Locale locale = Resources.getSystem().getConfiguration().locale;
        Log.e("SNN", "系统获取  :getLanguage : " +            Locale.getDefault().getLanguage());
        return locale;
    }

}

测试完毕,在8.0或更高版本可以正常切换多语言了。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 8.0 及以上版本,为了增强应用程序的安全性,Android 引入了后台限制,禁止未在前台运行的应用程序启动服务。如果您想在后台启动服务,需要使用 `startForegroundService()` 方法。这个方法会启动一个前台服务,然后你可以在服务启动后在通知栏显示一个通知,以此来告知用户服务正在运行。 以下是一个使用 `startForegroundService()` 的示例代码: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 创建一个 NotificationChannel NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT); // 向系统注册 NotificationChannel NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(channel); } // 创建一个 Intent,启动你的服务 Intent serviceIntent = new Intent(this, YourService.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 在 Android 8.0 及以上版本上,需要调用 startForegroundService() 方法启动服务。 startForegroundService(serviceIntent); } else { // 在 Android 8.0 以下版本上,可以直接调用 startService() 方法启动服务。 startService(serviceIntent); } ``` 注意:如果你使用的是 `startForeground()` 方法,会在 Android 8.0 及以上版本上抛出 `IllegalStateException` 异常,因为 Android 8.0 及以上版本禁止在后台启动服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值