目录

Adding App Icons to the Status Bar

After an app is integrated with the status bar, the status bar displays the app's custom icon. The icon supports displaying a custom pop-up when left-clicked, displaying a context menu when right-clicked, and receiving hover state callbacks. When the app exits, the status bar icon is automatically removed as the app process terminates.

API Description

The following lists the APIs related to operating an app icon in the status bar. For details, please refer to API Reference.

The APIs provided by Desktop Extension Kit take effect only on PCs/2-in-1 devices.

Table 1 APIs related to operating an app icon in the status bar

API Description
addToStatusBar(context: common.Context, statusBarItem: StatusBarItem): void Adds an app icon to the status bar.
removeFromStatusBar(context: common.Context): void Removes an app icon from the status bar.
updateQuickOperationHeight(context: common.Context, height: number): void Updates the height of the custom area in the pop-up window displayed when users click an app icon in the status bar.
updateStatusBarMenu(context: common.Context, statusBarGroupMenus: StatusBarGroupMenu[]): void Updates the information about menu items displayed when users right-click an app icon in the status bar.
updateStatusBarIcon(context: common.Context, statusBarIcon: StatusBarIcon): void Updates the icon in the status bar.
updateStatusBarHoverTips(context: common.Context, hoverTips: string): Promise<void> Updates the content displayed when the cursor hovers over an app icon in the status bar.
on(type: 'statusBarIconClick', callback: Callback<emitter.EventData>): void Listens for status bar icon click events.
off(type: 'statusBarIconClick', callback?: Callback<emitter.EventData>): void Unregisters listeners for status bar icon click events.
on(type: 'rightMenuClick', callback: Callback<emitter.EventData>): void Registers a listener for status bar context menu click events.
off(type: 'rightMenuClick', callback?: Callback<emitter.EventData>): void Unregisters the listener for status bar context menu click events.
updateStatusBarMenuItem(context: common.Context, item: StatusBarMenuItem): Promise<void> Updates the content of a level-1 menu item.
updateStatusBarSubMenuItem(context: common.Context, item: StatusBarSubMenuItem): Promise<void> Updates the content of a level-2 menu item.
isStatusBarCapabilitySupported(context: common.Context): Promise<boolean> Checks whether the status bar capability is supported. This API uses a promise to return the result.
onIconHover(callback: Callback<emitter.EventData>): void Registers a listener for status bar icon hover events. This API uses a callback to return the result asynchronously.
offIconHover(callback?: Callback<emitter.EventData>): void Unregisters the listener for status bar icon hover events. This API uses a callback to return the result asynchronously.

Development Procedure

  1. Import required modules.

    import { emitter } from '@kit.BasicServicesKit';
    import { statusBarManager } from '@kit.DeskTopExtensionKit';
    import { image } from '@kit.ImageKit';
    import { resourceManager } from '@kit.LocalizationKit';
  2. Create a MyStatusBarViewAbility.ets file (for example, in the entry/src/main/ets/statusbarviewextensionability folder) and a StatusBarPage page (for example, in the entry/src/main/ets/pages directory). This page is displayed in the pop-up window when users click an app icon in the status bar. Then build the custom StatusBarViewExtensionAbility.

    import { UIExtensionContentSession, Want } from '@kit.AbilityKit';
    import { StatusBarViewExtensionAbility } from '@kit.DeskTopExtensionKit';
    
    let TAG = 'MyStatusBarViewAbility';
    
    export default class MyStatusBarViewAbility extends StatusBarViewExtensionAbility {
      // Called when a StatusBarViewExtensionAbility component instance is created.
      onCreate() {
        console.info(TAG, 'onCreate');
      }
    
      // Called when a UIExtensionContentSession instance is created.
      onSessionCreate(want: Want, session: UIExtensionContentSession) {
        console.info(TAG, `onSessionCreate, want: ${want.abilityName}`);
        // pages/StatusBarPage is displayed in the pop-up window when users click an app icon in the status bar.
        session.loadContent('pages/StatusBarPage');
      }
    
      // Called when a StatusBarViewExtensionAbility component is initially launched into the foreground or transitions from the background to the foreground.
      onForeground() {
        console.info(TAG, 'onForeground');
      }
    
      // Called when a StatusBarViewExtensionAbility component transitions from the foreground to the background.
      onBackground() {
        console.info(TAG, 'onBackground');
      }
    
      // Called when a UIExtensionContentSession instance is destroyed.
      onSessionDestroy(session: UIExtensionContentSession) {
        console.info(TAG, 'onSessionDestroy');
      }
    
      // Called when a StatusBarViewExtensionAbility component instance is destroyed.
      onDestroy() {
        console.info(TAG, 'onDestroy');
      }
    }
  3. Configure the extension ability information in the module.json5 file of the module to which MyStatusBarViewAbility belongs.

    "extensionAbilities": [
        {
            "name": "MyStatusBarViewAbility",
            "icon": "$media:startIcon",
            "description": "statusBar",
            "type": "statusBarView",
            "exported": true,
            // File path to which the MyStatusBarViewAbility class belongs.
            "srcEntry": "./ets/statusbarviewextensionability/MyStatusBarViewAbility.ets"
        }
    ],
  4. In the rawfile folder (for example, entry/src/main/resources/rawfile) of the corresponding module, preset two 24 vp × 24 vp images (testWhite.svg and testBlack.svg in this example). Configure the icon information displayed in the status bar in the page component (for example, index.ets).

    /**
     * Context information can be obtained using the built-in method of the custom component.
     * Specific method: this.getUIContext().getHostContext()
     */
    if (!context) {
      console.error('getHostContext failed');
      return;
    }
    // Obtain a resource manager.
    const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
    
    // Create white pixelMap. You need to place the testWhite.svg image (24 vp × 24 vp) in the rawfile folder beforehand.
    const whiteFileData = resourceMgr.getRawFileContentSync('testWhite.svg');
    const whiteBuffer = whiteFileData.buffer;
    const whiteImageSource = image.createImageSource(whiteBuffer);
    let whitePixelMap = await whiteImageSource.createPixelMap();
    
    // Create black pixelMap. You need to place the testBlack.svg image (24 vp × 24 vp) in the rawfile folder beforehand.
    const blackFileData = resourceMgr.getRawFileContentSync('testBlack.svg');
    const blackBuffer = blackFileData.buffer;
    const blackImageSource = image.createImageSource(blackBuffer);
    let blackPixelMap = await blackImageSource.createPixelMap();
    
    // Build icon information.
    let icon: statusBarManager.StatusBarIcon = {
      white: whitePixelMap,
      black: blackPixelMap
    }
  5. Configure information about the pop-up window displayed when users click an app icon in the status bar.

    // Build information about the pop-up window displayed when users click an app icon in the status bar.
    let operation: statusBarManager.QuickOperation = {
      abilityName: 'MyStatusBarViewAbility',
      title: 'TestDemo',
      height: 300,
      // Can be left empty.
      moduleName: 'entry'
    };
  6. (Optional) Configure information about menu items displayed when users right-click an app icon in the status bar. You can add menu items to the status bar context menu. Regardless of whether a status bar context menu is configured, the system automatically generates the Exit menu item, which cannot be customized by apps. If an app supports language switching, the language of this item follows the system setting, but not the language setting of the app.

    // Build information about menu items displayed when users right-click an app icon in the status bar.
    let subMenus: statusBarManager.StatusBarSubMenuItem[] = [];
    let subMenuItemAction: statusBarManager.StatusBarMenuAction = {
      abilityName: 'EntryAbility'
    }
    let subMenu: statusBarManager.StatusBarSubMenuItem = {
      subTitle: 'Submenu Item',
      menuAction: subMenuItemAction
    }
    subMenus.push(subMenu);
    
    let statusBarMenuItems: statusBarManager.StatusBarMenuItem[] = [];
    let menuItem: statusBarManager.StatusBarMenuItem = {
      title: 'Level-1 Menu Item',
      // menuAction and subMenu cannot both be empty for a level-1 menu item.
      subMenu: subMenus
    };
    statusBarMenuItems.push(menuItem);
    
    let statusBarGroupMenus: statusBarManager.StatusBarGroupMenu[] = [];
    statusBarGroupMenus.push(statusBarMenuItems);
  7. After preparing the required configuration, call isStatusBarCapabilitySupported to determine whether the current device state supports integrating an icon into the status bar. If supported, call addToStatusBar to add the icon to the status bar and display the app icon. If not supported, calling addToStatusBar has no visible effect on the UI.

    // Build information about the icon added to the status bar.
    let item: statusBarManager.StatusBarItem = {
      icons: icon,
      quickOperation: operation,
      statusBarGroupMenu: statusBarGroupMenus,
      // Customize the content to be displayed when the icon is hovered during initialization.
      hoverTips: 'appName'
    };
    
    try {
      statusBarManager.addToStatusBar(context, item);
    } catch (error) {
      console.error(`addToStatusBar failed. error code: ${error.code}, error message: ${error.message}`);
    }
  8. (Optional) Call updateStatusBarMenu to update information about the menu items displayed when users right-click the app icon in the status bar.

    /**
     * Context information can be obtained using the built-in method of the custom component.
     * Specific method: this.getUIContext().getHostContext()
     */
    function updateStatusBarMenuExample(context: Context) {
      // Build information about menu items displayed when users right-click an app icon in the status bar.
      let subMenus: statusBarManager.StatusBarSubMenuItem[] = [];
      let subMenuItemAction: statusBarManager.StatusBarMenuAction = {
        abilityName: 'EntryAbility'
      }
      let subMenu: statusBarManager.StatusBarSubMenuItem = {
        subTitle: 'Level-2 Menu Item',
        menuAction: subMenuItemAction,
        menuCode: '00'
      }
      subMenus.push(subMenu);
    
      let statusBarMenuItems: statusBarManager.StatusBarMenuItem[] = [];
      let menuItem: statusBarManager.StatusBarMenuItem = {
        title: 'Level-1 Menu Item',
        menuCode: '0',
        // menuAction and subMenu cannot both be empty for a level-1 menu item.
        subMenu: subMenus
      };
      statusBarMenuItems.push(menuItem);
    
      let statusBarGroupMenus: statusBarManager.StatusBarGroupMenu[] = [];
      statusBarGroupMenus.push(statusBarMenuItems);
    
      if (!context) {
        console.error('getHostContext failed');
        return;
      }
      try {
        statusBarManager.updateStatusBarMenu(context, statusBarGroupMenus);
      } catch (error) {
        console.error(`updateStatusBarMenu failed. error code: ${error.code}, error message: ${error.message}`);
      }
    }
  9. (Optional) Call updateQuickOperationHeight to update the height of the pop-up window displayed when users click the app icon in the status bar.

    /**
     * Context information can be obtained using the built-in method of the custom component.
     * Specific method: this.getUIContext().getHostContext()
     */
    function updateQuickOperationHeightExample(context: Context) {
      if (!context) {
        console.error('getHostContext failed');
        return;
      }
      let height = 200;
      statusBarManager.updateQuickOperationHeight(context, height);
    }
  10. (Optional) Call updateStatusBarIcon to update the app icon in the status bar.

    /**
     * Context information can be obtained using the built-in method of the custom component.
     * Specific method: this.getUIContext().getHostContext()
     */
    async function updateStatusBarIconExample(context: Context) {
      if (!context) {
        console.error('getHostContext failed');
        return;
      }
      // Obtain a resource manager.
      const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
    
      // Create white pixelMap. You need to place the testWhite.svg image (24 vp × 24 vp) in the rawfile folder beforehand.
      const whiteFileData = resourceMgr.getRawFileContentSync('testWhite.svg');
      const whiteBuffer = whiteFileData.buffer;
      const whiteImageSource = image.createImageSource(whiteBuffer);
      let whitePixelMap = await whiteImageSource.createPixelMap();
    
      // Create black pixelMap. You need to place the testBlack.svg image (24 vp × 24 vp) in the rawfile folder beforehand.
      const blackFileData = resourceMgr.getRawFileContentSync('testBlack.svg');
      const blackBuffer = blackFileData.buffer;
      const blackImageSource = image.createImageSource(blackBuffer);
      let blackPixelMap = await blackImageSource.createPixelMap();
    
      // Build icon information.
      let icons: statusBarManager.StatusBarIcon = {
        white: whitePixelMap,
        black: blackPixelMap
      }
      statusBarManager.updateStatusBarIcon(context, icons);
    }
  11. (Optional) Call on/off to customize the pop-up window displayed when users click the app icon in the status bar if the abilityName of QuickOperation is not specified.

    function listenerLeftClickByOnOff() {
      let onStatusBarIconClick = (eventData: emitter.EventData) => {
        // Customize the pop-up window displayed when users click an app icon.
        let data = eventData.data;
        if (data) {
          switch (data['iconClickType']) {
            case 'leftClick':
              // Customize the pop-up window displayed when users click an app icon.
              break;
            default:
              break;
          }
        }
      }
    
      // Register a listener for status bar icon click events.
      statusBarManager.on('statusBarIconClick', onStatusBarIconClick);
    
      // Unregister the status bar icon click event. Always call the corresponding off method after calling on.
      statusBarManager.off('statusBarIconClick', onStatusBarIconClick);
    }
  12. (Optional) Call updateStatusBarMenu to specify notifyOnly and menuCode for StatusBarMenuAction and call on/off to customize the menu displayed when users right-click the app icon in the status bar.

    function listenerRightClickByOnOff() {
      let onRightMenuClick = (eventData: emitter.EventData) => {
        // Customize the menu displayed when users right-click an app icon.
        let data = eventData.data;
        if (data) {
          let menuCode = data['menuCode'] as string;
          // Process the click on a menu item.
        }
      }
    
      // Listen for click events on status bar icon context menu items.
      statusBarManager.on('rightMenuClick', onRightMenuClick);
    
      // Unregister the status bar icon context menu click event. Always call the corresponding off method after calling on.
      statusBarManager.off('rightMenuClick', onRightMenuClick);
    }
  13. (Optional) Call updateStatusBarHoverTips to customize the content displayed when the cursor hovers over the app icon in the status bar.

    /**
     * Context information can be obtained using the built-in method of the custom component.
     * Specific method: this.getUIContext().getHostContext()
     */
    async function updateStatusBarHoverTipsExample(context: Context) {
      if (!context) {
        console.error('getHostContext failed');
        return;
      }
      let hoverTips: string = 'hoverTips';
      try {
        await statusBarManager.updateStatusBarHoverTips(context, hoverTips);
      } catch (error) {
        console.error(`updateStatusBarHoverTips ${error.message} ${error.code}`)
      }
    }
  14. (Optional) If there are menu items and menuCode has been set for a level-1 menu item, you can call updateStatusBarMenuItem to update the content of the level-1 menu item based on the specified menuCode.

    /**
     * Context information can be obtained using the built-in method of the custom component.
     * Specific method: this.getUIContext().getHostContext()
     */
    async function updateStatusBarMenuItemExample(context: Context) {
      if (!context) {
        console.error('getHostContext failed');
        return;
      }
      // Obtain a resource manager.
      const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
    
      // Create white pixelMap. You need to place the testWhite.svg image (24 vp × 24 vp) in the rawfile folder beforehand.
      const whiteFileData = resourceMgr.getRawFileContentSync('testWhite.svg');
      const whiteBuffer = whiteFileData.buffer;
      const whiteImageSource = image.createImageSource(whiteBuffer);
      let whitePixelMap = await whiteImageSource.createPixelMap();
    
      // Create black pixelMap. You need to place the testBlack.svg image (24 vp × 24 vp) in the rawfile folder beforehand.
      const blackFileData = resourceMgr.getRawFileContentSync('testBlack.svg');
      const blackBuffer = blackFileData.buffer;
      const blackImageSource = image.createImageSource(blackBuffer);
      let blackPixelMap = await blackImageSource.createPixelMap();
    
      // Build icon information.
      let icon: statusBarManager.StatusBarItemIcon = {
        white: whitePixelMap,
        black: blackPixelMap
      }
    
      let menuItemOptions: statusBarManager.StatusBarMenuItemOptions = {
        icon: icon,
        selected: true
      }
    
      let menuAction: statusBarManager.StatusBarMenuAction = {
        abilityName: 'EntryAbility'
      }
    
      let menuItemTmp: statusBarManager.StatusBarMenuItem = {
        title: 'menuItem after',
        // The current menuCode must exist in an existing level-1 menu.
        menuCode: '0',
        // menuAction and subMenu cannot both be empty for a level-1 menu item.
        menuAction: menuAction,
        // Set the icon and whether the current menu item is selected.
        options: menuItemOptions
      }
    
      try {
        updateStatusBarMenuExample(context);
        await statusBarManager.updateStatusBarMenuItem(context, menuItemTmp);
      } catch (error) {
        console.error(`updateStatusBarMenuItem failed. error code: ${error?.code}, error message: ${error?.message}`);
      }
    }
  15. (Optional) If a level-1 menu item has level-2 menu items and menuCode has been set for level-2 menu items, you can call updateStatusBarSubMenuItem to update the content of a level-2 menu item based on the specified menuCode.

    /**
     * Context information can be obtained using the built-in method of the custom component.
     * Specific method: this.getUIContext().getHostContext()
     */
    async function updateStatusBarSubMenuItemExample(context: Context) {
      if (!context) {
        console.error('getHostContext failed');
        return;
      }
      // Obtain a resource manager.
      const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
    
      // Create white pixelMap. You need to place the testWhite.svg image (24 vp × 24 vp) in the rawfile folder beforehand.
      const whiteFileData = resourceMgr.getRawFileContentSync('testWhite.svg');
      const whiteBuffer = whiteFileData.buffer;
      const whiteImageSource = image.createImageSource(whiteBuffer);
      let whitePixelMap = await whiteImageSource.createPixelMap();
    
      // Create black pixelMap. You need to place the testBlack.svg image (24 vp × 24 vp) in the rawfile folder beforehand.
      const blackFileData = resourceMgr.getRawFileContentSync('testBlack.svg');
      const blackBuffer = blackFileData.buffer;
      const blackImageSource = image.createImageSource(blackBuffer);
      let blackPixelMap = await blackImageSource.createPixelMap();
    
      // Build icon information.
      let icon: statusBarManager.StatusBarItemIcon = {
        white: whitePixelMap,
        black: blackPixelMap
      }
      let subMenuItemOptions: statusBarManager.StatusBarMenuItemOptions = {
        icon: icon,
        selected: true
      }
      let menuAction: statusBarManager.StatusBarMenuAction = {
        abilityName: 'EntryAbility'
      }
      let subMenuItemTmp: statusBarManager.StatusBarSubMenuItem = {
        subTitle: 'menuItem',
        // The current menuCode must exist in an existing level-2 menu.
        menuCode: '00',
        menuAction: menuAction,
        // Set the icon and whether the current menu item is selected.
        options: subMenuItemOptions
      }
      try {
        updateStatusBarMenuExample(context);
        await statusBarManager.updateStatusBarSubMenuItem(context, subMenuItemTmp);
      } catch (error) {
        console.error(`updateStatusBarSubMenuItem failed. error code: ${error?.code}, error message: ${error?.message}`);
      }
    }
  16. (Optional) After the app is integrated with the status bar, call onIconHover/offIconHover to customize the hover service for the status bar icon.

    let onIconHoverChange = (eventData: emitter.EventData) => {
      let data = eventData.data;
      if (data) {
        let isHovered = data['isHovered'] as boolean;
        // Process the icon hover service.
      }
    };
    
    // Register a listener for status bar icon hover events.
    statusBarManager.onIconHover(onIconHoverChange);
    
    // Unregister the event callback handler.
    statusBarManager.offIconHover(onIconHoverChange);

Complete Sample Code

For the complete sample code, please refer to Desktop Extension Kit.