Obtaining the screen width and height of a device in HarmonyOS can be achieved through the DisplayManager and Display classes. This process can be broken down into the following steps:
-
Obtain a DisplayManager instance: First, obtain an instance of
DisplayManagerfrom the system service. -
Get the default display device: Use
DisplayManagerto retrieve the default display device, which is typically the main screen of the device. -
Read the screen dimensions: Extract the width and height of the screen from the obtained
Displayobject.
Below is a specific code example demonstrating how to implement this process in HarmonyOS:
javaimport ohos.aafwk.ability.Ability; import ohos.agp.window.service.Display; import ohos.agp.window.service.DisplayManager; import ohos.agp.window.service.Window; import ohos.app.Context; public class ScreenUtils { /** * Get screen width * @param context Context object * @return Screen width */ public static int getScreenWidth(Context context) { DisplayManager displayManager = DisplayManager.getInstance(); Display defaultDisplay = displayManager.getDefaultDisplay(context).get(); return defaultDisplay.getWidth(); } /** * Get screen height * @param context Context object * @return Screen height */ public static int getScreenHeight(Context context) { DisplayManager displayManager = DisplayManager.getInstance(); Display defaultDisplay = displayManager.getDefaultDisplay(context).get(); return defaultDisplay.getHeight(); } }
In the above code, we first obtain an instance of DisplayManager using DisplayManager.getInstance(). Then, we use the getDefaultDisplay() method to retrieve the default display device, which is typically the main screen of the device. Finally, we extract the screen width and height using the getWidth() and getHeight() methods respectively.
This approach is straightforward and enables quick retrieval of screen dimension information. When developing applications, understanding screen dimensions is particularly valuable for responsive design or dynamic layouts.