75 lines
2.1 KiB
Java
Raw Normal View History

2013-06-29 18:03:55 -07:00
package org.thoughtcrime.securesms.util;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
2013-06-29 18:03:55 -07:00
import android.content.Intent;
import android.content.res.Configuration;
2014-03-11 18:47:35 +01:00
import android.text.TextUtils;
2013-06-29 18:03:55 -07:00
import java.util.Locale;
public class DynamicLanguage {
private static final String DEFAULT = "zz";
private Locale currentLocale;
public void onCreate(Activity activity) {
currentLocale = getSelectedLocale(activity);
setContextLocale(activity, currentLocale);
2013-06-29 18:03:55 -07:00
}
public void onResume(Activity activity) {
2014-03-11 18:47:35 +01:00
if (!currentLocale.equals(getSelectedLocale(activity))) {
Intent intent = activity.getIntent();
activity.finish();
OverridePendingTransition.invoke(activity);
activity.startActivity(intent);
OverridePendingTransition.invoke(activity);
2013-06-29 18:03:55 -07:00
}
}
public void updateServiceLocale(Service service) {
currentLocale = getSelectedLocale(service);
setContextLocale(service, currentLocale);
}
public Locale getCurrentLocale() {
return currentLocale;
}
private static void setContextLocale(Context context, Locale selectedLocale) {
Configuration configuration = context.getResources().getConfiguration();
2013-06-29 18:03:55 -07:00
2014-03-11 18:47:35 +01:00
if (!configuration.locale.equals(selectedLocale)) {
2013-06-29 18:03:55 -07:00
configuration.locale = selectedLocale;
context.getResources().updateConfiguration(configuration,
context.getResources().getDisplayMetrics());
2013-06-29 18:03:55 -07:00
}
}
private static Locale getActivityLocale(Activity activity) {
return activity.getResources().getConfiguration().locale;
}
private static Locale getSelectedLocale(Context context) {
String language[] = TextUtils.split(TextSecurePreferences.getLanguage(context), "_");
2014-03-11 18:47:35 +01:00
if (language[0].equals(DEFAULT)) {
return Locale.getDefault();
} else if (language.length == 2) {
return new Locale(language[0], language[1]);
} else {
return new Locale(language[0]);
}
2013-06-29 18:03:55 -07:00
}
private static final class OverridePendingTransition {
static void invoke(Activity activity) {
activity.overridePendingTransition(0, 0);
}
}
}