我想通过我的xamarin本机应用程序更改设备语言。我可以使用android studio中的以下代码轻松完成此操作。
public static void changeLanguage()
throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
@SuppressWarnings("rawtypes")
Class amnClass = Class.forName("android.app.ActivityManagerNative");
Object amn = null;
Configuration config = null;
// amn = ActivityManagerNative.getDefault();
Method methodGetDefault = amnClass.getMethod("getDefault");
methodGetDefault.setAccessible(true);
amn = methodGetDefault.invoke(amnClass);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// getConfiguration moved from ActivityManagerNative to ActivityManagerProxy
amnClass = Class.forName(amn.getClass().getName());
}
// config = amn.getConfiguration();
Method methodGetConfiguration = amnClass.getMethod("getConfiguration");
methodGetConfiguration.setAccessible(true);
config = (Configuration) methodGetConfiguration.invoke(amn);
// config.userSetLocale = true;
@SuppressWarnings("rawtypes")
Class configClass = config.getClass();
Field f = configClass.getField("userSetLocale");
f.setBoolean(config, true);
Locale locale = new Locale("zh", "CN");
// set the locale to the new value
config.locale = locale;
// amn.updateConfiguration(config);
Method methodUpdateConfiguration = amnClass.getMethod("updateConfiguration", Configuration.class);
methodUpdateConfiguration.setAccessible(true);
methodUpdateConfiguration.invoke(amn, config);
}
我想通过Xamarin做同样的事情。但是在xamarin中它会抛出以下错误。
Caused by: java.lang.ClassNotFoundException: Didn't find class "Android.App.ActivityManagerNative"
请让我知道我可以在Xamarin中使用哪个课程来实现同样的目标?
答案 0 :(得分:1)
你能指导我哪里出错吗?或者,您可以与我分享您的项目吗?
这是我的代码:
var amnClass = Java.Lang.Class.ForName("android.app.ActivityManagerNative");
Java.Lang.Object amn = null;
Configuration config = null;
var methodGetDefault = amnClass.GetMethod("getDefault");
methodGetDefault.Accessible = true;
amn = methodGetDefault.Invoke(amnClass);
if (Build.VERSION.SdkInt >= Build.VERSION_CODES.O)
{
amnClass = Java.Lang.Class.ForName(amn.Class.Name);
}
var methodGetConfiguration = amnClass.GetMethod("getConfiguration");
methodGetConfiguration.Accessible = true;
config = methodGetConfiguration.Invoke(amn) as Configuration;
var configClass = config.Class;
var f = configClass.GetField("userSetLocale");
f.SetBoolean(config, true);
Locale locale = new Locale("zh", "CN");
config.Locale = locale;
var methodUpdateConfiguration = amnClass.GetMethod("updateConfiguration", Java.Lang.Class.FromType(typeof(Configuration)));
methodUpdateConfiguration.Accessible = true;
try
{
methodUpdateConfiguration.Invoke(amn, config);
}
catch (InvocationTargetException ee)
{
var error = ee.TargetException;
}
这是我的demo。