如何改变另一个应用程序的语言环境? [英] How to change locale of another app?

查看:158
本文介绍了如何改变另一个应用程序的语言环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以用这个code改变我的应用程序的语言环境:

I can change locale of my app using this code:

public static void setLocale(Locale locale) 
{
    Locale.setDefault(locale);
    Configuration appConfig = new Configuration();
    appConfig.locale = locale;
    App.context().getResources().updateConfiguration
            (appConfig,App.context().getResources().getDisplayMetrics());
} 

但如何与其他应用程序呢?

but how to do it with any other app?

推荐答案

完成!

我分享给其他用户my code!它采用当前活动的应用程序的名称在英语语言环境:

I'm sharing to other users my code! It takes name of current active app in English locale:

public static void setLocale(Locale locale, String packageName)
    {
        try
        {
            Context myAppContext = App.context();
            Context otherAppContext = myAppContext.createPackageContext(packageName, myAppContext.CONTEXT_IGNORE_SECURITY);         
            Locale.setDefault(locale);
            Configuration appConfig = new Configuration();
            appConfig.locale = locale;
            otherAppContext.getResources().updateConfiguration(appConfig, App.context().getResources().getDisplayMetrics());
        }
        catch(Throwable t){History.Error(t);}
    } 

    public static String getActive()
    {
        try
        {       
            PackageManager  pm          = App.context().getPackageManager();
            ActivityManager am          = (ActivityManager) App.context().getSystemService(App.context().ACTIVITY_SERVICE);
            RunningTaskInfo taskInfo    = am.getRunningTasks(1).get(0); // The first in the list of RunningTasks is always the foreground task.
            String          packageName = taskInfo.topActivity.getPackageName();            
            setLocale(new Locale("en-US"), packageName);        
            PackageInfo     appInfo     = pm.getPackageInfo(packageName, 0);
            String          label       = appInfo.applicationInfo.loadLabel(pm).toString();
            App.Toast(label);       
            return  label;
        }
        catch (Throwable t){History.Error(t);}
        return "???";
    }

这篇关于如何改变另一个应用程序的语言环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆