应用程序强制关闭后,以编程方式更改语言

时间:2017-01-17 15:23:54

标签: android xml configuration sdk localization

当我的应用因任何原因崩溃或强行关闭时,我点击“button”消息,然后点击“确定unfortunately the app has been stopped”。然后我的应用程序再次返回到同一个activity,但它在其他语言集中获取并调用OnResume()

我的问题是如何让我的应用返回到同一个Language config,即使我的应用因某些原因崩溃了。

我正在尝试刷新并在sharedPreferences中设置最后一个配置并刷新我的配置或内容视图但没有运气

代码:

 @Override
public void onResume(){
    super.onResume();

    if(appSharedPrefs.getBoolean("IsArabic",true)){
        Log.d("ERRRRR", "AR"); // that is called 
        setLocale(getApplicationContext(), "ar");
    }
    else{
        Log.d("ERRRRR", "EN");
        setLocale(getApplicationContext(), "en");
    }
}

protected  void setLocale(final Context ctx, final String lang)
{
    Log.d("ERRRRR", lang);

  /*  final Locale loc = new Locale(lang);
    Locale.setDefault(loc);
    final Configuration cfg = new Configuration();
    cfg.setLocale(loc);
    ctx.getResources().updateConfiguration(cfg, null);*/




    Resources res = ctx.getResources();
    // Change locale settings in the app.
    DisplayMetrics dm = res.getDisplayMetrics();
    android.content.res.Configuration conf = res.getConfiguration();
    conf.locale = new Locale(lang.toLowerCase());
    res.updateConfiguration(conf, dm);
}


@Override
public void onConfigurationChanged(Configuration newConfig) {
    Log.d("ERRRRR", "onConfigurationChanged");
    super.onConfigurationChanged(newConfig);
}

1 个答案:

答案 0 :(得分:0)

试试这个:

您可以抓住崩溃事件,并将activity加载到您想要的localeconfiguration ...

使用此实用程序类:

 public class ExceptionHandler implements
        Thread.UncaughtExceptionHandler {
    private final Activity myContext;


    public ExceptionHandler(Activity context) {
        myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {

        //you can show a dialog here telling that something went wrong
        Intent intent = new Intent(myContext, your_activity.class); //start your activity
        //put your locale you can use shared preference also
        intent.putExtra("locale", "ar");
        myContext.startActivity(intent);

        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }
}

现在在Mainactivity onCreate中使用它

Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));