Internationalization of HarmonyOS Next Applications: Language and Region Settings

xun_wang_6384a403f9817c2

SameX

Posted on November 14, 2024

Internationalization of HarmonyOS Next Applications: Language and Region Settings

This article aims to conduct an in-depth exploration of the technical details regarding language and region settings in the application internationalization of Huawei's HarmonyOS Next system (up to API 12 currently), summarizing based on actual development practices. Mainly serving as a vehicle for technical sharing and communication, it is inevitable that there may be errors and omissions. Colleagues are welcomed to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprinting must indicate the source and the original author.

In today's global application development, providing multi-language support and flexible region setting functions is the key to meeting the needs of different users. The HarmonyOS Next system offers developers rich tools and interfaces for handling language and region settings in applications. This article will introduce in detail how to obtain system language and region information, set application preferred languages, support multi-language switching, and handle problems related to language and region settings, hoping to serve as a starting point for further discussion.

I. Obtaining System Language and Region Information

(I) Obtaining the System Language

  1. Using the i18n.System.getSystemLanguage() Method     - This method returns the language code set in the current system, such as "zh" for Chinese, "en" for English, etc. When the application starts, this method can be called to obtain the system language, so that the corresponding interface display and resource loading can be carried out according to the user's language preference. For example:
import { i18n } from '@kit.LocalizationKit';
let systemLanguage = i18n.System.getSystemLanguage();
console.log("The current system language: ", systemLanguage);
Enter fullscreen mode Exit fullscreen mode
  1. The Significance and Use of Language Codes     - Language codes follow certain standards (such as the ISO - 639 standard). They are an important basis for the application to conduct language-related processing. By obtaining the system language code, the application can determine which language resource file to use and load the corresponding interface text, audio, etc., to achieve language localization display. For example, if the system language is "zh - Hans" (Simplified Chinese), the application can load the resource file of Simplified Chinese and display the Chinese interface to the user. ### (II) Obtaining the System Region
  2. Using the i18n.System.getSystemRegion() Method     - This method is used to obtain the region code set in the current system, such as "CN" for China, "US" for the United States, etc. Region codes are based on the ISO - 3166 standard. They can not only help the application determine the geographical region where the user is located but also be used for further region-specific settings, such as the adaptation of date formats, number formats, units of measurement, etc. For example:
import { i18n } from '@kit.LocalizationKit';
let systemRegion = i18n.System.getSystemRegion();
console.log("The current system region: ", systemRegion);
Enter fullscreen mode Exit fullscreen mode
  1. The Impact of Region Information on the Application     - Different regions may have different cultural habits and format specifications. For example, in terms of date format, some regions are accustomed to using "MM/DD/YYYY", while others may use "DD/MM/YYYY". After obtaining the system region information, the application can set the format according to the characteristics of the region to ensure that the date, time, number, etc. information seen by the user conforms to local habits. Meanwhile, the region information can also be used to provide localized services and content recommendations, such as displaying local weather information, news, etc. according to the region where the user is located. ### (III) Obtaining the System Locale (Locale)
  2. Using the i18n.System.getSystemLocale() Method     - This method returns the locale of the current system, which is a combination of language and region information, such as "zh - Hans - CN" representing Simplified Chinese and the Chinese region. The locale plays an important role in application internationalization and is a key basis for resource matching and loading. For example:
import { i18n } from '@kit.LocalizationKit';
let systemLocale = i18n.System.getSystemLocale();
console.log("The current system locale: ", systemLocale);
Enter fullscreen mode Exit fullscreen mode
  1. The Relationship between the Locale and Resource Loading     - The application usually looks for and loads the corresponding resource files according to the locale. In the resource directory structure, different subdirectories will be created according to the locale to store the resources of the corresponding language and region. After obtaining the system locale, the application can accurately locate and load the most suitable resources for the user, such as interface layout files, string resources, picture resources, etc., to achieve comprehensive localization. For example, if the system locale is "en - US", the application will look for and load resources in the "resources/en - US" directory to provide the English (American) version of the interface and content. ## II. Setting Application Preferred Languages ### (I) Methods for Setting Application Preferred Languages
  2. Using the i18n.System.setAppPreferredLanguage() Method     - Developers can use this method to set a specific preferred language for the application. For example, to set the application preferred language to Simplified Chinese:
import { i18n } from '@kit.LocalizationKit';
import {BusinessError } from '@kit.BasicServicesKit';
try {
    i18n.System.setAppPreferredLanguage("zh - Hans");
} catch(error) {
    let err: BusinessError = error as BusinessError;
    console.error(`Failed to set the application preferred language, error code: ${err.code}, message: ${err.message}.`);
}
Enter fullscreen mode Exit fullscreen mode
  1. Precautions     - Setting the application preferred language only affects the application itself and will not change the system language setting. This allows users to select another language for a specific application while the system language is set to one language. For example, if the user's system language is English but wishes that a certain application displays a Chinese interface, the user can set the preferred language to Chinese in that application. Meanwhile, after setting the preferred language, the application should immediately respond and load the corresponding language resources, update the interface display to provide a seamless language switching experience. ### (II) The Impact of Application Preferred Languages on the Application
  2. Resource Loading and Interface Display     - Once the application preferred language is set, during the application's startup or running process, resources will be preferentially loaded according to the preferred language. This includes all language-related resources such as interface text, pictures, audio, etc. For example, if the preferred language is French, the application will load French resources from the "resources/fr - FR" directory (assuming it exists) and display the French interface to the user. If the resources that exactly match the preferred language cannot be found, the application should load resources according to certain rules (such as reverting to the system language or the default language) to ensure that the application can run normally without crashing due to the lack of language resources.
  3. Function Adaptation and User Experience     - According to the preferred language, the application can also conduct function adaptation. For example, in some language environments, it may be necessary to adjust input methods, keyboard layouts, date and time formats, etc. For applications that support voice input, the corresponding voice recognition model can also be selected according to the preferred language to improve the accuracy of voice input. Through these adaptation measures, the application can provide users with a functional experience that is more in line with their language habits and usage scenarios, enhancing users' satisfaction and loyalty to the application. ## III. Supporting Multi-Language Switching ### (I) Implementation Methods of Multi-Language Switching
  4. Interface Interaction Design     - Provide language switching options in the application's settings interface or other appropriate locations. For example, a drop-down menu or list can be created to display all the languages supported by the application, allowing users to easily select the language they want. When the user selects a new language, the application should trigger the language switching logic.
  5. Language Switching Logic Processing     - When the user selects a new language, the application calls the i18n.System.setAppPreferredLanguage() method to set the new preferred language. Then, the current interface or the entire application is reloaded to apply the new language settings. During the reloading process, the application re-obtains and displays resources according to the new preferred language, updating the interface text, pictures, etc. For example:
// Assume that the language switching is handled in a function on a language settings page
function changeLanguage(languageCode: string) {
    try {
        i18n.System.setAppPreferredLanguage(languageCode);
        // Reload the current page or the entire application (here, it is assumed that reloading is achieved by re-navigating to the current page, but the actual situation may be more complex)
        window.location.reload();
    } catch(error) {
        let err: BusinessError = error as BusinessError;
        console.error(`Failed to switch languages, error code: ${err.code}, message: ${err.message}.`);
    }
}
Enter fullscreen mode Exit fullscreen mode

(II) User Experience Optimization for Multi-Language Switching

  1. Real-Time Feedback and Transition Effects     - Immediately give feedback after the user selects a language, such as displaying a brief prompt message to inform the user that the language switching is in progress. Meanwhile, some transition effects can be added, such as fade animations, to make the interface switching more natural and smooth, reducing the user's waiting and discomfort. For example, when the user clicks on the language switching option, a prompt box saying "Switching languages, please wait..." is displayed in the center of the screen, and the interface gradually fades to white. After the new language interface is loaded, it fades in and is displayed.
  2. Saving User Language Preferences     - The application should remember the user's selected language preferences and automatically apply the language settings when starting next time. The user's selected language preferences can be stored in local storage (such as the application's internal database or file), and read and set the preferred language when the application starts. This way, the user does not need to select the language every time the application starts, improving the convenience of use. For example:
// Save language preferences
function saveLanguagePreference(languageCode: string) {
    // Here, it is assumed that a simple method of local storage is used, but the actual situation may require a more complex storage mechanism
    localStorage.setItem("preferredLanguage", languageCode);
}
// Read language preferences and set
function loadLanguagePreference() {
    let languageCode = localStorage.getItem("preferredLanguage");
    if (languageCode) {
        try {
            i18n.System.setAppPreferredLanguage(languageCode);
        } catch(error) {
            let err: BusinessError = error as BusinessError;
            console.error(`Failed to set the application preferred language, error code: ${err.code}, message: ${err.message}.`);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

(III) Testing and Verification of Multi-Language Switching

  1. Comprehensive Testing of Different Language Combinations     - Test all language combinations supported by the application to ensure that the application's functions are normal, the interface display is correct, and the resource loading is error-free under various language switching situations. This includes switching from one language to another and switching languages multiple times. For example, test switching from English to Chinese and then from Chinese to French, and check whether the interface text, date format, number format, etc. are correctly displayed after each switch, and whether the application's various functions (such as button clicks, input box inputs, etc.) work normally.
  2. Testing Boundary Conditions and Special Characters     - Pay attention to testing boundary conditions, such as when switching to a language with fewer language resources or more complex special character handling, whether the application can correctly handle it. For example, for languages with complex writing systems (such as Arabic, Hebrew, etc., which are written from right to left) or special characters (such as rare Chinese characters, special kana combinations in Japanese, etc.), check whether the interface layout is reasonable, whether the text display is complete and clear, and whether the input and output are normal. Meanwhile, test the interaction with other system functions (such as notifications, sharing, etc.) during the language switching process to ensure the stability and reliability of the application in a multi-language environment. ## IV. Handling Problems Related to Language and Region Settings ### (I) Problem of Missing Language Resources
  3. Problem Description     - When the application cannot find resources that match the user's language preference or the system language in certain situations, it may lead to abnormal interface display, such as displaying garbled characters, missing some text, or displaying the text of the default language. For example, if an application supports English and Chinese, but the user's device system language is set to a language that the application does not fully support (such as Spanish), and the application does not provide Spanish resources, interface display problems may occur.
  4. Solution     - Establish a reasonable resource fallback mechanism. When the exact matching resources cannot be found, the application can search for other available resources according to a certain priority order. The usual priority order can be: user preferred language > system language > default language (such as English or the base language specified by the application developer). For example, if Spanish resources cannot be found, the application can try to find the resources of the user preferred language (if any), if not, then search for the resources of the system language, and finally use the default language resources to ensure that the application can display basic content normally instead of crashing or displaying chaos. Meanwhile, during the development process, try to comprehensively support common languages to reduce the possibility of resource shortage. If it is found that the resources of certain languages are often missing or incomplete, consider increasing support for these languages to improve the internationalization degree of the application. ### (II) Problem of Region Format Adaptation
  5. Problem Description     - Different regions have different requirements for date, time, number, currency, etc. formats, and the application may not be able to correctly adapt to these region formats. For example, in a global application, if the date display is not set correctly according to the region where the user is located, it may lead to misinterpretation of the date information by the user. In some regions, the date format is "DD/MM/YYYY", while in other regions it may be "MM/DD/YYYY" or "YYYY - MM - DD".
  6. Solution     - Use the formatting classes and methods provided by the system for region format adaptation. For date and time, use the DateTimeFormat class, and select the appropriate format style for formatting according to the region identifier of the user's location. For example:
import { intl } from '@kit.LocalizationKit';
let date = new Date(2023, 9, 15);
let dateFormat = new intl.DateTimeFormat("en - GB", {dateStyle: "long"}); // Set the date format according to the British region format
let formattedDate = dateFormat.format(date); // Displays as "15 October 2023"
let timeFormat = new intl.DateTimeFormat("en - GB", {timeStyle: "medium"}); // Set the time format according to the British region format
let formattedTime = timeFormat.format(date); // Displays as "15:00:00" (assuming the current time is 3 PM)
Enter fullscreen mode Exit fullscreen mode

    - For numbers and currency, use the NumberFormat class for formatting. For example:

import { intl } from '@kit.LocalizationKit';
let numberFormat = new intl.NumberFormat("en - US", {style: "currency", currency: "USD"}); // Set the currency format according to the American region format
let formattedNumber = numberFormat.format(1234.56); // Displays as "$1,234.56"
let numberFormat2 = new intl.NumberFormat("fr - FR", {style: "number", minimumFractionDigits: 2}); // Set the number format according to the French region format
let formattedNumber2 = numberFormat2.format(1234.56); // Displays as "1 234,56" (Note that in the French number format, a comma is used as the decimal point and a space is used as the number grouping symbol)
Enter fullscreen mode Exit fullscreen mode

    - Through this way, the application can accurately display date, time, number, and currency information according to the region where the user is located, improving the consistency and accuracy of the user experience.

(III) Problem of Data Consistency during Language Switching

  1. Problem Description     - During the multi-language switching process, the data in the application may become inconsistent. For example, the data input by the user in one language environment may not be correctly displayed or interpreted after switching languages. Or, some cached data, setting information, etc. in the application may be incompatible with the new language environment, leading to abnormal functions. For example, in a shopping application, if the user adds items to the shopping cart in the English interface and then switches to the Chinese interface, the item information in the shopping cart may display garbled characters or the total price cannot be correctly calculated.
  2. Solution     - Adopt a unified encoding and format standard in the data storage and processing process to ensure that the data is language-independent. For example, for text data, use a universal encoding format such as UTF - 8 to avoid character encoding problems caused by language switching. For the setting and configuration information in the application, conduct language-independent storage and management. When switching languages, re-interpret and display these information according to the new language environment. For the parts involving data calculation and processing, ensure that the algorithms and logic are not affected by the language. For example, in the calculation of the total price of the shopping cart, use a unified number format and calculation rules, rather than relying on the display format in a specific language environment. Meanwhile, after switching languages, reload and refresh the relevant data to ensure that the displayed information is consistent with the new language environment. For example, in the shopping application, after switching languages, re-obtain the item information in the shopping cart, format and display it according to the new language environment, and re-calculate the total price and other related data to ensure the consistency and correctness of the data.

(IV) Problem of Dynamic Language Update

  1. Solution     - Monitor the change events of the system language or application preferred language. The HarmonyOS system may provide corresponding language change listeners. Developers can register this listener to be immediately notified when the language changes. For example:
import { i18n } from '@kit.LocalizationKit';
i18n.System.on('languageChange', () => {
    // Processing logic when the language changes
    let newLanguage = i18n.System.getSystemLanguage();
    console.log("The system language has been changed to: ", newLanguage);
    // Reload resources here and update the interface language
    loadResourcesForLanguage(newLanguage);
});
Enter fullscreen mode Exit fullscreen mode

    - After receiving the language change notification, immediately reload the resources of the current interface or the entire application and apply the new language settings. The resource loading and interface update logic can be encapsulated into a function (such as loadResourcesForLanguage() in the above code), and this function can be called for processing when the language changes. In this way, the application can respond to language changes in real - time, providing more dynamic and flexible language support and improving the user experience.

(V) Compatibility Problem of Different System Versions

  1. Problem Description     - With the continuous upgrade of the HarmonyOS system, the functions and interfaces related to language and region settings may change. When the application runs on different versions of the system, compatibility problems may be encountered. For example, older versions of the system may not support new language setting methods, or new versions of the system may modify the behavior of certain interfaces, resulting in abnormalities in the application on old or new versions of the system. For example, in the early versions of the HarmonyOS system, the language setting interface may be different from the current version. If the application directly uses the new version of the interface, an error will be reported when running on the old version of the system.
  2. Solution     - Conduct version compatibility testing during the development process. Conduct language and region setting function tests for different versions of the HarmonyOS system respectively to ensure that the application can work normally on each version. Conditional compilation or runtime detection of the system version can be used to call the corresponding language setting interface according to different versions. For example:
import device from '@ohos.device';
device.getInfo().then((info) => {
    let systemVersion = info.version;
    if (systemVersion >= "5.0.0") {
        // Use the new version of the language setting interface
        i18n.System.setAppPreferredLanguageV5("zh - Hans");
    } else {
        // Use the old version of the language setting interface (assuming it is setAppPreferredLanguageV4)
        i18n.System.setAppPreferredLanguageV4("zh - Hans");
    }
});
Enter fullscreen mode Exit fullscreen mode

    - At the same time, pay attention to the official documentation and version update instructions of the HarmonyOS system, timely understand the changes in functions related to language and region settings, and make adaptation work in advance. If possible, keep the flexibility of the application's code structure so that interface adjustments and function optimizations can be more easily carried out during system upgrades. For example, encapsulate the code related to language settings into an independent module. When the system version changes, only the interface calls in this module need to be modified without affecting the entire application's architecture.

(VI) Problem of Permissions for Language and Region Settings

  1. Problem Description     - In some cases, the application may require specific permissions to obtain or set system language and region information. If the application does not obtain the corresponding permissions, it may not be able to conduct normal operations related to language and region settings, resulting in limited functions. For example, in some devices or system environments with high security requirements, the application may require the user's explicit authorization to obtain system language information. Otherwise, when calling methods such as i18n.System.getSystemLanguage(), it may fail.
  2. Solution     - Clearly declare the required permissions for language and region settings in the application's permission declaration. For example, add the permission declaration in the application's config.json file:
{
    "module": {
        "reqPermissions": [
            {
                "name": "ohos.permission.GET_SYSTEM_LOCALE",
                "reason": "Used to obtain system language and region information to provide localized services",
                "usedScene": {
                    "ability": [
                        "com.example.myapp.MainAbility"
                    ],
                    "when": "always"
                }
            }
        ]
    }
}
Enter fullscreen mode Exit fullscreen mode

    - Check whether the corresponding permissions have been obtained during the application's runtime. If the permissions have not been obtained, guide the user to manually grant the permissions. For example:

import permission from '@ohos.permission';
async function checkPermission() {
    let hasPermission = await permission.checkPermission('ohos.permission.GET_SYSTEM_LOCALE');
    if (!hasPermission) {
        try {
            await permission.requestPermissionsFromUser(['ohos.permission.GET_SYSTEM_LOCALE']);
        } catch (error) {
            console.error('Failed to request permission: ', error);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

    - Through this way, ensure that the application conducts language and region setting operations with the corresponding permissions, avoiding abnormal functions due to permission problems. At the same time, reasonably explain to the user the reasons for applying for permissions to increase the user's willingness to grant permissions.

(VII) Problem of Synchronization between In - application Language and System Language

  1. Problem Description     - When the system language changes, the application may not be able to synchronize with the system language in a timely manner, resulting in the language display in the application being inconsistent with the system language. For example, the user changes the language in the system settings, but the application still uses the previous language setting until the user manually switches the language within the application, which brings inconvenience to the user.
  2. Solution     - In addition to monitoring the system language change event (as described above), the application can also actively check whether the system language has changed when starting or resuming from the background, and update the in - application language according to the change situation. For example:
import { i18n } from '@kit.LocalizationKit';
function checkAndSyncLanguage() {
    let currentSystemLanguage = i18n.System.getSystemLanguage();
    let savedAppLanguage = localStorage.getItem('appLanguage'); // Assume that the previously saved in - application language setting is stored in local storage
    if (currentSystemLanguage!== savedAppLanguage) {
        // The system language and the in - application language are inconsistent, conduct synchronization
        i18n.System.setAppPreferredLanguage(currentSystemLanguage);
        localStorage.setItem('appLanguage', currentSystemLanguage);
        // Reload resources and update the interface language
        loadResourcesForLanguage(currentSystemLanguage);
    }
}
// Call when the application starts
checkAndSyncLanguage();
// It can also be called when the application resumes from the background (assuming the application has corresponding life - cycle hook functions)
application.on('resume', () => {
    checkAndSyncLanguage();
});
Enter fullscreen mode Exit fullscreen mode

    - Through this active checking and synchronization method, the application can better keep consistent with the system language, providing a more continuous user experience. At the same time, when synchronizing the language, pay attention to saving the user's personalized language settings within the application (if any) to avoid losing the user's preferences due to the synchronization operation.

(VIII) Problem of Language Settings in a Multi - user Environment

  1. Problem Description     - On devices that support multiple users, different users may have different language preferences. The application needs to be able to correctly handle language settings in a multi - user environment to ensure that each user can see an interface in the language that matches their preference. For example, on a family - shared device, parents and children may use different languages respectively. The application should display according to the language preference of the currently logged - in user.
  2. Solution     - The HarmonyOS system may provide an interface to obtain the current logged - in user information. The application can use this interface to obtain the current user identifier, and then associate the corresponding language preference setting according to the user identifier. For example:
import userIAM from '@ohos.userIAM';
userIAM.getUserInfo().then((userInfo) => {
    let userId = userInfo.userId;
    // Look for the corresponding language preference setting according to userId (assuming that the language preference setting is stored in the local database or server)
    let preferredLanguage = getPreferredLanguageForUser(userId);
    i18n.System.setAppPreferredLanguage(preferredLanguage);
    // Load the corresponding language resources and display the interface
    loadResourcesForLanguage(preferredLanguage);
});
Enter fullscreen mode Exit fullscreen mode

    - When the user switches, update the application's language settings in a timely manner. Listen to the user switching event, and re - obtain the new user's language preference and set it in the event handling function. For example:

userIAM.on('userSwitch', (newUserId) => {
    let preferredLanguage = getPreferredLanguageForUser(newUserId);
    i18n.System.setAppPreferredLanguage(preferredLanguage);
    // Reload resources and update the interface language
    loadResourcesForUser(newUserId, preferredLanguage);
});
Enter fullscreen mode Exit fullscreen mode

    - Through this way, the application can correctly handle language settings in a multi - user environment, providing each user with a personalized language experience. At the same time, pay attention to reasonable optimization of resource management and loading in a multi - user environment to avoid resource waste or slow loading due to frequent user switching.
Through the effective handling of these problems related to language and region settings, we can create more stable, flexible, and user - friendly HarmonyOS Next applications. On the internationalization path, continuously focusing on user needs, system updates, and best practices, and continuously optimizing the language and region setting functions of the application will help improve the application's competitiveness and user satisfaction, making it better adapt to the needs of the global market. It is hoped that this article can provide comprehensive and practical references and guidance for HarmonyOS system colleagues in handling language and region settings, helping applications achieve success in the internationalization process.

💖 💪 🙅 🚩
xun_wang_6384a403f9817c2
SameX

Posted on November 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related