Three methods of language switching

Source: Internet
Author: User

Android has done a good job in international and multi-language switching. An application only needs to name the values-[language] folder of the corresponding language family, you can switch between multiple languages by using "Settings"> "Language & keyboard"> "Select language.

But how to implement it in the application? The following methods have been found on the Internet after searching:[Java]
View plaincopy

  1. Resources res = getresources ();
  2. Configuration Config = res. getconfiguration ();
  3. Config. locale = locale;
  4. Displaymetrics dm = res. getdisplaymetrics ();
  5. Res. updateconfiguration (config, DM );


The test failed. Well, it's time for programmers to be self-reliant. The following describes three methods for multi-language switching.

First:

 

The principle of the first two methods is to implement "Select language" in the application ". By viewing the source code, the core code is:

[Java]
View plaincopy
  1. Iactivitymanager iactmag = activitymanagernative. getdefault ();
  2. Try {
  3. Configuration Config = iactmag. getconfiguration ();
  4. Config. locale = locale;
  5. // Permission must be declared here: android. permission. CHANGE_CONFIGURATION
  6. // OnCreate () will be called again ();
  7. IActMag. updateConfiguration (config );
  8. } Catch (RemoteException e ){
  9. E. printStackTrace ();
  10. }
  11. PS: Thanks to Zeng Yang for his help.

It can be found that both IActivityManager and ActivityManagerNative are non-public classes. How to call it? The first is API spoofing, and the second is Java reflection.
1. API Spoofing
Android. jar, which is burned to a mobile phone, contains various types and methods required by Android. jar, which is only part of android. jar, is used by developers. API spoofing refers to simulating undisclosed classes and methods in an application so that the application can compile and generate an APK, however, what is called in the actual operation of the application is still the real android in the mobile phone. jar.

The core code shows that the two methods getconfiguration () and updateconfiguration (config) in activitymanagernative are simulated ). With reference to the source code, the engineering structure diagram and Code Simulation of the application are as follows:

Engineering Structure:

Code:

[Java]
View plaincopy
  1. ActivityManagerNative. java
  2. Package android. app;
  3. /**
  4. * @ Author Sodino E-mail: sodinoopen@hotmail.com
  5. * @ Version Time: 11:37:01
  6. */
  7. Public abstract class ActivityManagerNative {
  8. Public static iactivitymanager getdefault (){
  9. Return NULL;
  10. }
  11. }
  12. Iactivitymanager. Java
  13. Package Android. app;
  14. Import Android. content. res. configuration;
  15. Import Android. OS. RemoteException;
  16. /**
  17. * @ Author sodino E-mail: sodinoopen@hotmail.com
  18. * @ Version time: 11:37:46
  19. */
  20. Public abstract interface iactivitymanager {
  21. Public abstract Configuration getConfiguration () throws RemoteException;
  22. Public abstract void updateConfiguration (Configuration paramConfiguration)
  23. Throws RemoteException;
  24. }

After simulating these two classes, you can use the core code of the conversion language mentioned above.

2. Java reflection mechanism
Not to mention, Java reflection mechanism getting started Tutorial:
Http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html
I have written several examples of using Java reflection:
[Android] Get uninstalled APK icons (original non-post)
Http://blog.csdn.net/sodino/article/details/6215224
[Android] hanging up and answering calls
Http://blog.csdn.net/sodino/article/details/6181610

Directly run the Code:

[Java]
View plaincopy
  1. Private void updateLanguage (Locale locale ){
  2. Log. d ("ANDROID_LAB", locale. toString ());
  3. Try {
  4. Object objIActMag, objActMagNative;
  5. Class clzIActMag = Class. forName ("android. app. IActivityManager ");
  6. Class clzActMagNative = Class. forName ("android. app. ActivityManagerNative ");
  7. Method mtdActMagNative $ getDefault = clzActMagNative. getDeclaredMethod ("getDefault ");
  8. // IActivityManager iActMag = ActivityManagerNative. getDefault ();
  9. ObjIActMag = mtdActMagNative $ getDefault. invoke (clzActMagNative );
  10. // Configuration config = iActMag. getConfiguration ();
  11. Method mtdIActMag $ getConfiguration = clzIActMag. getDeclaredMethod ("getConfiguration ");
  12. Configuration config = (Configuration) mtdIActMag $ getConfiguration. invoke (objIActMag );
  13. Config. locale = locale;
  14. // IActMag. updateConfiguration (config );
  15. // Permission must be declared here: android. permission. CHANGE_CONFIGURATION
  16. // OnCreate () will be called again ();
  17. Class [] clzParams = {Configuration. class };
  18. Method mtdIActMag $ updateConfiguration = clzIActMag. getDeclaredMethod (
  19. "UpdateConfiguration", clzParams );
  20. MtdIActMag $ updateConfiguration. invoke (objIActMag, config );
  21. } Catch (Exception e ){
  22. E. printStackTrace ();
  23. }
  24. }

After the actual operation, we found that after setting a new locale for the current system, not only did our application languages change, but all the application languages of the system have changed. This must be unreasonable. One solution is to set locale to the system before exiting the application interface. However, I do not like this method. In addition, after calling the updateconfiguration () method, the entire activity will be re-oncreate (), which may be difficult to consider the life cycle of the activity. So there is the third method below.

3. Change the language system by yourself (haha, this name is very realistic)
What is the significance of the existence of programmers.
It is a bit difficult to switch the language system by yourself. first look at the engineering structure:

The content of values/strings. XML is the same as that of XML/English. xml; the content of values-ZH-RCN/strings. XML is the same as that of XML/Chinese. xml. The reason for this redundancy is that when the APK is generated, all the content in values hits RASC and cannot be read.

The following considerations must be taken into account to achieve the transformation of the language family:
3.1 R. XXXXX. ID corresponds to the text string in the corresponding language family (Special consideration must be given to the R. array. String Array ).
3.2 Parse XML.
3.3 After the language family is set, all interface elements are refreshed manually.

Declare a string in xml in this format:

[Html]
View plaincopy
  1. <String name = "app_name"> language application </string>

The corresponding R file will generate an id to refer to this string[Java]
View plaincopy

  1. Public static final class string {
  2. Public static final int app_name = 0x7f050001;
  3. }

The 3.1 problem is how to match the id and string. The solution is as follows:[Java]
View plaincopy

  1. Resources res = context. getResources ();
  2. String pkg = context. getPackageName ();
  3. String tag = "app_name ";
  4. Int idTag = res. getIdentifier (tag, "string", pkg );

3.2 Parse XML
A new tool is used here: XmlResourceParser. The parsing process is a bit winding, but it is simpler than SAX. For details, see the code in the LanguageApp_Sodino project.

3.3 manually refresh the interface.
To obtain all the indexes that involve the update components of the language family, you can perform manual work with some effort.

For detailed implementation process, see the following three projects:
LanguageApp_APICheat
LanguageApp_Reflection
LanguageApp_Sodino
(PS: Don't ask me why the downloaded project cannot be directly used in IDE, why is it a bunch of garbled red forks to be opened, since it is a programmer, should I think more about the problem .)
This article is owned by sodino, A csdn blog blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.