Dev*_*unt 11 android localization sharedpreferences android-activity
我创建了一个活动,用于更改应用程序的语言环境以加载所选语言的资源,然后重新启动应用程序,而且在通过以下代码设置语言环境后,我使用sharedpreferences将整数值保留为应用程序状态,下次打开应用程序时,提到的状态没有正确的值!!!!但是,当我删除语言设置时,应用程序的状态没有任何问题!
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
/*
* Intent refresh = new Intent(this, AndroidLocalizeActivity.class);
* startActivity(refresh); finish();
*/
PrefManager _p = new PrefManager(getApplicationContext(), PrefConfigNames.LANGUAGE_APP_CONFIG);
_p.setStringValue(GeneralPrefKeyNames.LANGUAGE, lang);
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
setResult(RESULT_OK, null);
finish();
Run Code Online (Sandbox Code Playgroud)
我不知道共享偏好会发生什么(我在这个应用程序中使用了开源安全首选项(CodeProject文章))
这里!!!
提前致谢
编辑#1 PrefManager.java
public class PrefManager {
private SecurePreferences _securePreferences = null;
public PrefManager(Context context, String PrefName)
{
_securePreferences = new SecurePreferences(context, PrefName);
}
public void setStringValue(String key, String value)
{
_securePreferences.edit().putString(key, value).commit();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑#2 有些奇怪的是,当我从eclipse调试或运行应用程序时,存储在sharedprefs中的应用程序的状态具有正确的值(调试或作为android应用程序运行)!!!但是当我重新运行它时手机它有默认值!!!请帮我解决这个问题!
编辑#3 我发现使用以下行重新启动应用程序时出现问题,是否有另一种方法可以重新启动应用程序而没有任何问题???甚至更好的方法(更新语言而不重新启动应用程序)?
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)
我尝试了以下链接来实现第二个提到的方法
,但在下一行之后不会被提出
res.updateConfiguration(conf, dm);
Run Code Online (Sandbox Code Playgroud)
提前致谢
我终于得到了解决方案,在 onPause 方法中,我将当前保存的语言保存在共享首选项中,并在设置活动中更改区域设置并返回到 onResume 方法中的上一个活动后,我将新保存的语言与保存在onPause,如果这两个不相等,我调用 recreate 方法。
@Override
protected void onResume()
{
super.onResume();
SharedPreferences _sPreferences = getSharedPreferences(PrefConfigNames.LANGUAGE_APP_CONFIG,
Context.MODE_PRIVATE);
String resumeLang = _sPreferences.getString(GeneralPrefKeyNames.LANGUAGE, "En");
if (!currentLang.equals(resumeLang))
recreate();
};
@Override
protected void onPause()
{
SharedPreferences _sPreferences = getSharedPreferences(PrefConfigNames.LANGUAGE_APP_CONFIG,
Context.MODE_PRIVATE);
currentLang = _sPreferences.getString(GeneralPrefKeyNames.LANGUAGE, "En");
super.onPause();
};
Run Code Online (Sandbox Code Playgroud)