Example usage for android.content.res Configuration setLocale

List of usage examples for android.content.res Configuration setLocale

Introduction

In this page you can find the example usage for android.content.res Configuration setLocale.

Prototype

public void setLocale(@Nullable Locale loc) 

Source Link

Document

Set the locale list to a list of just one locale.

Usage

From source file:Main.java

/**
 * Setting {@link Locale} for {@link Context}.
 *///from  w  w  w .  j av  a2s. c om
public static Context applyLanguageForContext(Context context, Locale locale) {
    Resources resources = context.getResources();
    Configuration config = resources.getConfiguration();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        config.setLocale(locale);
        return context.createConfigurationContext(config);
    } else {
        config.locale = locale;
        resources.updateConfiguration(config, resources.getDisplayMetrics());
        return context;
    }
}

From source file:eu.faircode.netguard.ServiceJob.java

private static void submit(Rule rule, PersistableBundle bundle, Context context) {
    PackageManager pm = context.getPackageManager();
    JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);

    // Get english application label
    String label = null;//from w ww.j a  v a2s.  c o m
    try {
        Configuration config = new Configuration();
        config.setLocale(new Locale("en"));
        Resources res = pm.getResourcesForApplication(rule.info.packageName);
        res.updateConfiguration(config, res.getDisplayMetrics());
        label = res.getString(rule.info.applicationInfo.labelRes);
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        CharSequence cs = rule.info.applicationInfo.loadLabel(pm);
        if (cs != null)
            label = cs.toString();
    }

    // Add application data
    bundle.putInt("uid", rule.info.applicationInfo.uid);
    bundle.putString("package", rule.info.packageName);
    bundle.putInt("version_code", rule.info.versionCode);
    bundle.putString("version_name", rule.info.versionName);
    bundle.putString("label", label);
    bundle.putInt("system", rule.system ? 1 : 0);
    try {
        bundle.putString("installer", pm.getInstallerPackageName(rule.info.packageName));
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        bundle.putString("installer", null);
    }

    // Cancel overlapping jobs
    for (JobInfo pending : scheduler.getAllPendingJobs()) {
        String type = pending.getExtras().getString("type");
        if (type != null && type.equals(bundle.getString("type"))) {
            if (type.equals("rule")) {
                int uid = pending.getExtras().getInt("uid");
                if (uid == bundle.getInt("uid")) {
                    Log.i(TAG, "Canceling id=" + pending.getId());
                    scheduler.cancel(pending.getId());
                }
            } else if (type.equals("host")) {
                int uid = pending.getExtras().getInt("uid");
                int version = pending.getExtras().getInt("version");
                int protocol = pending.getExtras().getInt("protocol");
                String daddr = pending.getExtras().getString("daddr");
                int dport = pending.getExtras().getInt("dport");
                if (uid == bundle.getInt("uid") && version == bundle.getInt("version")
                        && protocol == bundle.getInt("protocol") && daddr != null
                        && daddr.equals(bundle.getString("daddr")) && dport == bundle.getInt("dport")) {
                    Log.i(TAG, "Canceling id=" + pending.getId());
                    scheduler.cancel(pending.getId());
                }
            }
        }
    }

    // Schedule job
    ComponentName serviceName = new ComponentName(context, ServiceJob.class);
    JobInfo job = new JobInfo.Builder(++id, serviceName).setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
            .setMinimumLatency(Util.isDebuggable(context) ? 10 * 1000 : 60 * 1000).setExtras(bundle)
            .setPersisted(true).build();
    if (scheduler.schedule(job) == JobScheduler.RESULT_SUCCESS)
        Log.i(TAG, "Scheduled job=" + job.getId() + " success");
    else
        Log.e(TAG, "Scheduled job=" + job.getId() + " failed");
}

From source file:com.jarklee.materialdatetimepicker.Utils.java

public static String getStringFromLocale(@NonNull Context context, @StringRes int strRes, Locale locale) {
    if (locale == null) {
        return context.getString(strRes);
    }//www  . j  a  v  a2 s  . c om
    Resources standardResources = context.getResources();
    AssetManager assets = standardResources.getAssets();
    DisplayMetrics metrics = standardResources.getDisplayMetrics();
    Configuration config = new Configuration(standardResources.getConfiguration());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        config.setLocale(locale);
    } else {
        config.locale = locale;
    }
    Resources defaultResources = new Resources(assets, metrics, config);
    try {
        return defaultResources.getString(strRes);
    } catch (Exception e) {
        return context.getString(strRes);
    }
}

From source file:im.vector.VectorApp.java

/**
 * Get String from a locale//from   w  ww  . ja  va  2s . c om
 *
 * @param context    the context
 * @param locale     the locale
 * @param resourceId the string resource id
 * @return the localized string
 */
private static String getString(Context context, Locale locale, int resourceId) {
    String result;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Configuration config = new Configuration(context.getResources().getConfiguration());
        config.setLocale(locale);
        try {
            result = context.createConfigurationContext(config).getText(resourceId).toString();
        } catch (Exception e) {
            Log.e(LOG_TAG, "## getString() failed : " + e.getMessage());
            // use the default one
            result = context.getString(resourceId);
        }
    } else {
        Resources resources = context.getResources();
        Configuration conf = resources.getConfiguration();
        Locale savedLocale = conf.locale;
        conf.locale = locale;
        resources.updateConfiguration(conf, null);

        // retrieve resources from desired locale
        result = resources.getString(resourceId);

        // restore original locale
        conf.locale = savedLocale;
        resources.updateConfiguration(conf, null);
    }

    return result;
}

From source file:im.vector.VectorApp.java

/**
 * Compute a localised context/*from  w w  w  . j  a  va 2 s. c  o m*/
 *
 * @param context the context
 * @return the localised context
 */
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static Context getLocalisedContext(Context context) {
    try {
        Resources resources = context.getResources();
        Locale locale = getApplicationLocale();
        Configuration configuration = resources.getConfiguration();
        configuration.fontScale = getFontScaleValue();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            configuration.setLocale(locale);
            configuration.setLayoutDirection(locale);
            return context.createConfigurationContext(configuration);
        } else {
            configuration.locale = locale;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLayoutDirection(locale);
            }
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
            return context;
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "## getLocalisedContext() failed : " + e.getMessage());
    }

    return context;
}

From source file:com.money.manager.ex.core.Core.java

private void setAppLocale_Internal(String languageToLoad) {
    Locale locale;/*from   ww  w  .j  ava  2  s. c  o  m*/

    if (!TextUtils.isEmpty(languageToLoad)) {
        locale = new Locale(languageToLoad);
        //                locale = Locale.forLanguageTag(languageToLoad);
    } else {
        locale = Locale.getDefault();
    }
    // http://developer.android.com/reference/java/util/Locale.html#setDefault%28java.util.Locale%29
    //            Locale.setDefault(locale);

    // change locale of the configuration
    Resources resources = getContext().getResources();
    Configuration config = resources.getConfiguration();

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        config.locale = locale;
    } else {
        config.setLocale(locale);
    }

    // set new locale
    resources.updateConfiguration(config, resources.getDisplayMetrics());
}

From source file:divya.myvision.TessActivity.java

public void setLang(String lang) {
    Locale locale;/*w  w  w  .j a v  a 2  s .  co m*/
    if (lang.equals("Spanish")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                Locale locSpanish = new Locale("spa", "MEX");
                tts.setLanguage(locSpanish);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("spa", "MEX");
    }

    else if (lang.equals("French")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                tts.setLanguage(Locale.FRENCH);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("fr");
    } else if (lang.equals("Japanese")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                tts.setLanguage(Locale.JAPANESE);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("ja");
    } else if (lang.equals("Chinese")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                tts.setLanguage(Locale.CHINESE);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("zh");
    } else if (lang.equals("German")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                tts.setLanguage(Locale.GERMAN);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("de");
    } else if (lang.equals("Italian")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                tts.setLanguage(Locale.ITALIAN);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("it");
    } else if (lang.equals("Korean")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                tts.setLanguage(Locale.KOREAN);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("ko");
    } else if (lang.equals("Hindi")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                Locale locHindhi = new Locale("hi");
                tts.setLanguage(locHindhi);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("hi");
    } else if (lang.equals("Russian")) {
        // Set up the Text To Speech engine.
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                Locale locHindhi = new Locale("ru");
                tts.setLanguage(locHindhi);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("ru");
    } else {
        TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(final int status) {
                tts.setLanguage(Locale.US);
            }
        };
        tts = new TextToSpeech(this.getApplicationContext(), listener);
        locale = new Locale("en");
    }
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.setLocale(locale);
    this.getApplicationContext().getResources().updateConfiguration(config, null);

}

From source file:org.dbhatt.d_deleted_contact.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_restore_all:
        if (Build.VERSION.SDK_INT > 22) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
                restore_all_contacts();/*from   ww w . j av  a 2 s  .  c om*/
            } else {
                final MainActivity mainActivity = this;
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.WRITE_CONTACTS)) {
                    new AlertDialog.Builder(this).setTitle(R.string.permission)
                            .setMessage(R.string.permission_message_write_external_storage)
                            .setPositiveButton(R.string.permission_grant,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish_activity = false;
                                            ActivityCompat.requestPermissions(mainActivity,
                                                    new String[] { Manifest.permission.WRITE_CONTACTS },
                                                    REQUEST_WRITE_CONTACTS_CONTACT);
                                        }
                                    })
                            .create().show();
                } else {
                    finish_activity = false;
                    ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_CONTACTS },
                            REQUEST_WRITE_CONTACTS_CONTACT);
                }
            }
        } else {
            restore_all_contacts();
        }
        break;
    case R.id.action_app_invite:
        finish_activity = false;
        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(AppInvite.API)
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                    }
                }).build();
        Intent app_invite_intent = new AppInviteInvitation.IntentBuilder(getString(R.string.invite_title))
                .setMessage(getString(R.string.invite_message))
                .setEmailSubject(getString(R.string.invite_email_subject))
                .setEmailHtmlContent("<html><h2 class='h2'><a href='%%APPINVITE_LINK_PLACEHOLDER%%'>"
                        + getString(R.string.app_name) + "</a></h2></html>")
                .build();
        startActivityForResult(app_invite_intent, APP_INVITE);
        break;

    case R.id.action_share:
        finish_activity = false;
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("application/zip");
        intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(getApplicationInfo().sourceDir)));
        startActivityForResult(Intent.createChooser(intent, getString(R.string.share)), APP_INVITE);
        break;

    case R.id.action_contact_us:
        finish_activity = false;
        startActivityForResult(new Intent(getApplicationContext(), Contact_us.class),
                DO_NOT_FINISH_REQUEST_CODE);
        break;
    case R.id.action_refresh:
        if (refreshing)
            Toast.makeText(this, R.string.try_after_some_time, Toast.LENGTH_SHORT).show();
        else
            load_contacts();
        break;
    case R.id.action_language:
        try {
            new AlertDialog.Builder(this).setTitle(R.string.action_language)
                    .setNegativeButton(R.string.dismiss, null)
                    .setItems(R.array.languages, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Locale locale = new Locale(getApplicationContext().getResources()
                                    .getStringArray(R.array.language_code)[which]);
                            Locale.setDefault(locale);
                            Configuration config = new Configuration();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
                                config.setLocale(locale);
                            else
                                config.locale = locale;
                            getApplicationContext().getResources().updateConfiguration(config, null);
                            startActivity(new Intent(getApplicationContext(), Splash.class));
                            finish();
                        }
                    }).create().show();
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.android.server.MountService.java

private void copyLocaleFromMountService() {
    String systemLocale;/*from  w w  w.  j  ava  2s  .  co m*/
    try {
        systemLocale = getField(StorageManager.SYSTEM_LOCALE_KEY);
    } catch (RemoteException e) {
        return;
    }
    if (TextUtils.isEmpty(systemLocale)) {
        return;
    }

    Slog.d(TAG, "Got locale " + systemLocale + " from mount service");
    Locale locale = Locale.forLanguageTag(systemLocale);
    Configuration config = new Configuration();
    config.setLocale(locale);
    try {
        ActivityManagerNative.getDefault().updateConfiguration(config);
    } catch (RemoteException e) {
        Slog.e(TAG, "Error setting system locale from mount service", e);
    }

    // Temporary workaround for http://b/17945169.
    Slog.d(TAG, "Setting system properties to " + systemLocale + " from mount service");
    SystemProperties.set("persist.sys.language", locale.getLanguage());
    SystemProperties.set("persist.sys.country", locale.getCountry());
}