Hongmeng Ability development-Creation and use of Ability under the Stage model

Create Ability and Page pages

Create two Ability: EntryAbility and DetailsAbility. EntryAbility is created by default by the project. Here we only talk about how to create DetailsAbility.

  • Use DevEco Studio, select the corresponding module, right-click the mouse, select New > Ability, and modify the name in the dialog box to create the related Ability.
  • After creating the Ability, we need to set the page for the Ability. Select the pages directory, right-click the mouse, select New > Page, and modify the name in the dialog box to create the relevant Page.
// DetailsPage.ets
...
@Entry
@Component
struct DetailsPage {
  private goodsDetails: GoodsData = new GoodsData();

  aboutToAppear() {
    if (position !== undefined) {
      this.goodsDetails = viewModel.loadDetails(position);
    }
  }

  build() {
    Column() {
      Scroll() {
        Column() {
          Stack({ alignContent: Alignment.Top }) {
            // 商品图片预览组件
            PreviewerComponent({ goodsImg: this.goodsDetails.goodsImg })
            this.TopBarLayout()
          }
          .height(DetailsPageStyle.TOP_LAYOUT_HEIGHT)
          .width(PERCENTAGE_100)
          .backgroundColor($r('app.color.background1'))
          // 展示商品信息的卡片布局
          this.CardsLayout()
        }.width(PERCENTAGE_100)
      }
      .height(DetailsPageStyle.SCROLL_LAYOUT_WEIGHT)
      .backgroundColor($r('app.color.background'))
      // 底部工具栏
      BottomBarComponent().height(DetailsPageStyle.TOOLBAR_WEIGHT)
    }
    .height(PERCENTAGE_100)
    .width(PERCENTAGE_100)
  }
  ...
}

Use windowStage.loadContent to set the relevant Page page for the specified Ability.

// DetailsAbility.ts
...
export default class DetailsAbility extends UIAbility {
  ...
  onWindowStageCreate(windowStage) {
    ...
    windowStage.loadContent('pages/DetailsPage', (err, data) => {
      if (err.code) {
        hilog.error(DETAIL_ABILITY_DOMAIN, TAG, 'Failed. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(DETAIL_ABILITY_DOMAIN, TAG, 'Succeeded. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }
  ...
};

UIAbilityContext module enables the ability of Ability

The UIAbilityContext module provides the ability to access specific Ability resources, including starting and stopping the Ability, obtaining the caller communication interface, and raising a pop-up window to request user authorization.

In the shopping application, when we click on a product in the product list on the homepage, we can jump to the product details page. The ability to start Ability of the UIAbilityContext module is used here. Regarding the method of obtaining UIAbilityContext, it is recommended to use the getContext(this) method to obtain UIAbilityContext.

// HomePage.ets
...
  build() {
    Column() {
      Column() {
        Blank().height(HomePageStyle.BLANK_HEIGHT)
        // Logo和二维码区域
        TopBarComponent()
          .padding({
            top: HomePageStyle.PADDING_VERTICAL,
            bottom: HomePageStyle.PADDING_VERTICAL,
            left: HomePageStyle.PADDING_HORIZONTAL,
            right: HomePageStyle.PADDING_HORIZONTAL
          })
        SearchComponent()
        TabsComponent({ tabMenus: this.tabMenus })
        BannerComponent({ bannerList: this.bannerList })
        MenusComponent({ menus: this.menus })
        // 商品列表组件
        GoodsComponent({ goodsList: this.goodsList, startPage: (index) => {
          let handler = getContext(this) as AppContext.UIAbilityContext;
          viewModel.startDetailsAbility(handler, index);
        } })
      }
      .width(PERCENTAGE_100)
    }
    .height(PERCENTAGE_100)
    .backgroundImage($rawfile('index/index_background.png'), ImageRepeat.NoRepeat)
    .backgroundImageSize(ImageSize.Cover)
  }
 ...

The startDetailsAbility method calls the UIAbilityContext module's ability to start Ability.

// HomeViewModel.ets
... 
  public startDetailsAbility(context: common.UIAbilityContext, index: number): void {
    const want: Want = {
      bundleName: getContext(context).applicationInfo.name,
      abilityName: DETAILS_ABILITY_NAME,
      parameters: {
        position: index
      }
    };
    try {
      context.startAbility(want);
    } catch (error) {
      hilog.error(HOME_PAGE_DOMAIN, TAG, '%{public}s', error);
    }
  }
...

Information transmission carrierWant

Want is a carrier of information transfer between objects and can be used to transfer information between application components. One of the usage scenarios of Want is as a parameter of startAbility, which contains the specified startup target and related data that needs to be carried at startup.

// DetailsAbility.ts
...
export default class DetailsAbility extends UIAbility {
    onCreate(want, launchParam) {
        let index: number = want?.parameters?.position;
        AppStorage.SetOrCreate(KEY, index);
        hilog.info(DETAIL_ABILITY_DOMAIN, TAG, '%{public}s', 'Ability onCreate');
    }
    ...
};

In the DetailsPage page, use AppStorage to obtain the detailWant object, parse the product information parameters in the detailWant object, and call the loadDetails method to display product details.

// DetailsPage.ets
...
let viewModel: DetailsViewModel = new DetailsViewModel();
const KEY: string = 'GoodsPosition';
let position = AppStorage.Get<number>(KEY);
...
@Entry
@Component
struct DetailsPage {
  private goodsDetails: GoodsData = new GoodsData();

  aboutToAppear() {
    if (position !== undefined) {
      this.goodsDetails = viewModel.loadDetails(position);
    }
  }
 ...
}

Use HiLog to print life cycle functions

The HiLog logging system allows applications to print log content according to specified types, specified levels, and specified format strings, helping developers understand the running status of applications/services and better debug programs. HiLog provides debug, info, warn, error and fatal interfaces. In shopping applications, we use hilog to print the life cycles of EntryAbility and DetailsAbility. Before printing, we need to know three parameters:

  • domain: Domain identifier corresponding to the log, ranging from 0x0~0xFFFF. It is recommended that developers customize the divisions within the application as needed.
  • tag: Specifies the log ID, which can be any string. It is recommended to be used to identify the class or business behavior where the call is located.
  • level: log level.
  • format: format string, used for formatted output of logs. Multiple parameters can be set in the format string, and the parameters need to include parameter type and privacy identifier. Privacy flags are divided into {public} and {private}, and the default is {private}. The content marked {public} is output in clear text, and the content marked {private} is filtered and echoed.

Below we demonstrate in EntryAbility how to use the hilog object to print the Ability life cycle function onBackground.

At this time, when we click on the product in the product list, the system will open the product details page, and the EntryAbility hosting the product list view will return to the background. The system will execute the onBackground() method of EntryAbility. We can observe the relevant life cycle in the console of DevEco Studio The transformation of the function.

// EntryAbility.ts
...
export default class EntryAbility extends UIAbility {
    ...
    onBackground() {
        // Ability has back to background
        hilog.isLoggable(ENTRY_ABILITY_DOMAIN, TAG, hilog.LogLevel.INFO);
        hilog.info(ENTRY_ABILITY_DOMAIN, TAG, '%{public}s', 'Ability onBackground');
    }
}

The content of this article is a simple application of Ability development technology in Hongmeng development. For more Hongmeng development technologies, you can go to my homepage to check. Here is the technology distribution of Hongmeng Development 4.0 (thumbnail):

Find and save the high-definition full version of the technical learning roadmap below (with Hongmeng documents attached)

Based on the Stage model, the creation and use of Ability are explained. First in the course, we will lead you to use DevEco Studio to create a Stage model Ability, and use UIAbilityContext to start another Ability, and then use Want to pass parameters between Abilities. Finally, we use HiLog to print the life cycle of the Ability. The effect diagram is shown in the figure:

Guess you like

Origin blog.csdn.net/m0_70748845/article/details/135458460