Android Nougat 7.1 resets Locale after launching W

2019-02-03 09:02发布

We got a weird behavior with Android N 7.1 ( API-25 ) That after Launching WebView, system enforces reseting Locale to device locale. That overrides used locale (for localization) on application. Easy way to reproduce that is to get a localization on app. and launch a WebView. Then you won't see localized content any more until you relaunching app again. That happens only on Android-7.1 (API-25)

Here is how I switch Locale which is working in all APIs:

 public void switchToCzLocale() {
        Locale mLocale = new Locale("cs","CZ");// it can be any other Locale
        Configuration config = getBaseContext().getResources()
                .getConfiguration();
        Locale.setDefault(mLocale);
        config.setLocale(mLocale);
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }

I have uploaded a sample to reproduce that issue with more details on:

https://github.com/mabuthraa/WebView-android7-issue

Please any idea if this behavior is a bug or probably bad implantation of changing locale.

Here is the link to issue ticket on Android group: Issue 218310: [developer preview] Creating a WebView resets Locale to user defaults

1条回答
神经病院院长
2楼-- · 2019-02-03 09:37

Here is my workaround solution.

We resolved that issue by enforcing setting locale again after initializing webView and before loading content:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  MyApp.getApplication().switchToCzLocale();
}

For example in WebActivity:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        mWebView = (WebView) findViewById(R.id.webview);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
          MyApp.getApplication().switchToCzLocale();
        }
        mWebView.loadData(getString(R.string.web_content), "text/html", "charset=UTF-8");
    }

MyApp:

import android.app.Application;
import android.content.res.Configuration;

import java.util.Locale;


public class MyApp extends Application {
    private static MyApp sApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        switchToCzLocale();
        sApplication = this;
    }

    public static MyApp getApplication() {
        return sApplication;
    }

    public void switchToCzLocale() {
        Locale mLocale = new Locale("cs","CZ");
        Configuration config = getBaseContext().getResources()
                .getConfiguration();
        Locale.setDefault(mLocale);
        config.setLocale(mLocale);
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }
}

I hope that may help,'.

Still Im looking for a better solution.

查看更多
登录 后发表回答